JavaScript fails parsing JSON name key with “-” character

Tricky question here.

I have a function that modifies the content of a given JSON string by using osa script native JavaScript capabilities:

function set_json {
    local json_source_data="$1"
    local json_key="$2"
    local json_key_value="$3"

    if [[ "$#" -lt "3" ]]; then
        echo "Arguments missing. You must provide at least three valid arguments: set_json json_source_data json_key json_key_value"
        return 1
    fi

        read -r -d '' js_code_to_run <<EOF
const env = $.NSProcessInfo.processInfo.environment.objectForKey('json_content').js;
parsedJSON = JSON.parse(env);
parsedJSON.$json_key = '$json_key_value';
modified_json = JSON.stringify(parsedJSON, null, 2);
modified_json
EOF

    json_data_modified=$(json_content="$json_source_data" /usr/bin/osascript -l "JavaScript" <<< "${js_code_to_run}")

    if [[ -n $json_data_modified ]]; then
        echo "$json_data_modified"
    else
        return 1
    fi
}

It works perfectly fine for standard JSON name-value pairs with names like “whatever” or “what_ever”.

The problem is, some names have been given (improperly IMO) names such as: “name-key”.

This causes the function to crash:

115:145: syntax error: Error on line 3: SyntaxError: Left hand side of operator '=' must be a reference. (-2700)

As apparently the “-” causes JS to mess things up. I am finding a way to take the $json_key variable I am passing escaped (taking the “-” in “name-key” as a string, not something else) but I can’t find a way to do so given my poor JavaScript skills.

Help is welcome!

JavaScript string method localeCompare() accepts ‘undefined’ and refuse ‘null’ as a ‘locale’ param

I found some approach to sort string in natural way

const rows = ['37-SK', '4-ML', '41-NP', '2-YZ', '21', '26-BF'];
console.log(rows.sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })));

it outputs following:

0: "2-YZ"
1: "4-ML"
2: "21"
3: "26-BF"
4: "37-SK"
5: "41-NP"
length: 6
[[Prototype]]: Array(0)

but when i replace undefined with null

console.log(rows.sort((a, b) => a.localeCompare(b, null, { numeric: true, sensitivity: 'base' })));

it outputs:

Uncaught TypeError: Cannot convert undefined or null to object
    at String.localeCompare (<anonymous>)
    at natSort.js:2:35
    at Array.sort (<anonymous>)
    at natSort.js:2:18

Why?

Google Admin SDK – JSON Object field named ‘0’?

I currently am working with the Google Admin SDK, fetching data about some users. I can access and display the data in paths like “console.log(user.name.fullName);”, but there is a field, like “Location” of a user, and it’s nested in JSON path: users -> organizations -> 0 -> location.

My problem is the function “console.log(user.organizations.0.location)” won’t work, since there is a number “0”.

Can someone suggest how I get into that “0” path? Sorry if worded badly, I’m new to APIs and terminology here.

Thank you.

Why does my Leetcode submission show “wrong answer when it works when I run it? [duplicate]

I created a solution to a Leetcode problem.

I am supposed to find the longest substring in a string without repeating characters.

Below is my code:

let lengthOfLongestSubstring = (s) => {
    let result = [];
    for (let i = 0; i < s.length; i++) {
        result.push([]);
        let n = i;
        while (s[n] && !result[i].includes(s[n])) {
            result[i].push(s[n]);
            n++;
        }
        result[i] = result[i].length;
    }
    return Math.max(...result);
}

When I try to submit it, I get the below error message:
Error message

What is the reason for this?

PS: You are not allowed to change the name of the function.

How to make complete form in which background color of button changes when user starts typing in input field with javascript , html and css?

This is Html code :-

<body>
    <div class="container">
        <input id="username" placeholder="Username" class="input"/>
        <button disabled id="btn" type="button" class="button">Submit</button>
    </div>
</body>

This is My Javscript Code :-

const btn = document.getElementById("btn");
const inputfield = document.getElementById("username");

inputfield.addEventListener("keyup", function(e){
    const val = e.target.value;
    if(val === ""){
        btn.disabled = true;
        btn.style.backgroundColor = "grey";
    }else {
        btn.disabled = false;
        btn.style.backgroundColor = "orange";
    }
})

Now the issue is that it only works for one input and the associated button field
it does not work for another pair of input field and button , so what changes should i make in the above javascript code in which it runs for as many as input field and button i want?

Please can anyone help me in this. Thank you

If you have full jquery code it’s also accepted.

Trying to make a function out of a test

I have some code as part of a test to call a graphql endpoint. It is using super test, so

it('should test stuff', () => done {
    const someGraphQL = `mutation {.....}`
    
    let the_id = ""

    request
    .post("/graphql") 
    .send({
        query: someGraphQL
    })
    .set("Accept", "application/json")
    .expect(200)
    .end((err, res) => {
        if (err) return done(err);
        the_id = res.body.data.id;
        done();
    })
    done()
})

and that works fine. I wanted to create a function which did the same and could be callable. So I created this in a different file

function addThing (title) {
    const someGraphQL = `mutation {.....}`
    
    let the_id = ""

    request
    .post("/graphql") 
    .send({
        query: someGraphQL
    })
    .set("Accept", "application/json")
    .expect(200)
    .end((err, res) => {
        if (err) return done(err);
        the_id = res.body.data.id;
    })
}

Now the code runs, but without a callback, it will error as taking too long. I’ve never tried this before, so unsure how to add a callback to a function (like this) – I did try adding => done { but got a syntax error.

Type error when using onMutate in react query (Optimistic Updates)

export const usePostApi = () =>
  useMutation(['key'], (data: FormData) => api.postFilesImages({ requestBody: data }));

Query Definition

const { mutateAsync } = usePostApi();

  const {data} = await mutateAsync(formData, {
      onMutate: () => {},
    });

component

After defining the query in one place, it is called and used in the component. When calling mutateAsync from a component, an option is provided as the second argument, but if onMutate is put, the following type error occurs. Any idea how to solve it?

error message : Argument of type '{ onMutate: () => void; }' is not assignable to parameter of type 'MutateOptions<ResponseData<PostFilesImagesResponse>, unknown, FormData, unknown>'.   Object literal may only specify known properties, and 'onMutate' does not exist in type 'MutateOptions<ResponseData<PostFilesImagesResponse>, unknown, FormData, unknown>'.

Frontend End Point POST wrong (Hosted On Netlify)

When I am going to post a call it is working fine locally and I am able to make the access with netlify but once I am hosting the front end app from Netlify the the POST Proxy is getting set to the netlify URL

The hosted URL : https://deploy-preview-14–hungry-lovelace-df4f46.netlify.app/login

One we click on Sign Up and click on Signup then I see the POST method is going to
https://deploy-preview-14–hungry-lovelace-df4f46.netlify.app/register

where I need it to go to https://ns-db-2022.herokuapp.com/register

In local I made it work by adding Proxy: ‘https://ns-db-2022.herokuapp.com’ in the Package.json

But once I host it I am not able to post the call, what should I do ?

Screenshot for the same has been added as well as the above URL it can be done online.

Because of which I am getting 404 error Page not found
enter image description here

html2canvas works on jsfiddle but doesn’t work on my site

based on https://jsfiddle.net/Sq7hg/3120/
it’s pure JS – without any library – but it works on jsfiddle
on my site – and also here – it doesn’t work
I’m getting error – html2canvas is not defined
please help

html2canvas([document.getElementById('mydiv')], {
    onrendered: function (canvas) {
        document.getElementById('canvas').appendChild(canvas);
        var data = canvas.toDataURL('image/png');
        var image = new Image();
        image.src = data;
        document.getElementById('image').appendChild(image);
    }
});
#mydiv {
    background-color: lightblue;
    width: 100px;
    height: 100px
}
<div id="mydiv"><p>text!</p></div>
<br><br>
 <div id="canvas"><p>Canvas:</p></div>
 <div id="image"><p>Image:</p></div>

Autocomplete search with link on Name

I want to click on name in search box and open profile of that person. How can I add link on this item.firstname. My route for user profile is ‘/users/{id}’..

this is my javascript code for autocomplete

<script type="text/javascript">
        $('.livesearch').select2({
            placeholder: 'Search users',
            ajax: {
                url: '/master/autocomplete',
                dataType: 'json',
                delay: 250,
                processResults: function (data) {
                    return {
                        results: $.map(data, function (item) {
                            return {
                                text: item.firstname+' '+item.lastname,
                                id: item.id,

                            }
                        })
                    };
                },
                cache: true,
            }
        });
    </script>

enter image description here

Javascript and bootstrap won’t work together

I have a product list, I made a js file which ads filter buttons and a search bar which works well but when I put it in my html file it stops working because of the Bootstrap link.
When I remove bootstrap 5.1.4 link code<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> then js content works well (but i lose my bootstrap designs). Basically both won’t work when on the same page i don’t understant why.

my code : https://jsfiddle.net/q69b1c0y/2/

Dynamically groupby on an array of objects by number of equal characters

What is the best way to groupby objects in an array ?

For example, given this array of objects:

[ 
    { MachineName: "10020784 machineTypeA P.", Value: "5" },
    { MachineName: "80346 machineTypeA s", Value: "10" },
    { MachineName: "80349 machineTypeA k", Value: "15" },
    { MachineName: "80427 machineTypeA w", Value: "20" },
    { MachineName: "machineTypeX", Value: "25" },
    { MachineName: "machineTypeX", Value: "30" },
    { MachineName: "machineTypeX", Value: "35" },
    { MachineName: "machineTypeOther", Value: "40" }
    { MachineName: "machineTypeOther", Value: "40" }
    
]

What I’m looking for would be able to total specific values (if requested).

So if I did groupby MachineName, I’d want to receive:

  [
        { MachineName: " machineTypeA .", Value: "50" },
        { MachineName: "machineTypeX", Value: "90" },
        { MachineName: "other", Value: "80" } 
  ]

I currently use the Array.prototype.some() function :

    Ausgabe = []    
    _.forEach(data, element => {  
          
          obj = {
         
            MachineName: element.MachineName,
            Value: element.Value,
          
          }
        Ausgabe.push(obj);
        
        })
        
         items1 = Ausgabe.filter(item => item.Anlage.indexOf('machineTypeA') !== -1);
         items2 = Ausgabe.filter(item => item.Anlage.indexOf('machineTypeX') !== -1);
         items3 = Ausgabe.filter(item => item.Anlage.indexOf('machineType') !== -1);

if (items1.length <= null){

} 
else {
for (var i = 0; i < items1.length; i++){ // DZ
  if (items1[i].Value <= null){
    //count ++;
     object1 = {
    MachineName : 'machineTypeA', 
  }   
}  else {
     if (items1[i].Value != null){
     object1 = {
    MachineName:'machineTypeA',
    Value: items1[i].Value , 
    
  }  
}
} 
}
 Ausgabe2.push(object1)
}

if (items2.length  <= null){

} else {
for (var i = 0; i < items2.length; i++){ // DZ
  if (items2[i].Value <= 0){
    //count ++;
     object2 = {
    MachineName : 'machineTypeX', 
  }   
}  else {
     if (items1[i].MRT != null){
     object2 = {
    Value : 'machineTypeX',
    MachineName : items2[i].Value , 
  }  
}
} 
}
 Ausgabe2.push(object2)
}


if(items3.length <= null){

} 
else {
for (var i = 0; i < items3.length; i++){ // DZ
  if (items3[i].Value <= 0){
    //count ++;
     object3 = {
    MachineName : 'machineTypeOther', 
  }   
}  else {
     if (items3[i].Value != null){
     object3 = {
    MachineName : 'machineTypeOther',
    Value : items3[i].Value , 
    
  }  
}
} 
}
 Ausgabe2.push(object3)
}

The problem I have with this solution is that its fine for a small array ,
but for a larger arrays its ineffective because I would need to create x number of ‘items’.

If the MachineName would be equal I could use the following :

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

Is there a way to look for x amount of equal characters in a row and then group them accordingly ?