javascriptarraysjsonobject

Generate a JSON from two arrays


I have to arrays which are related.

shortArray = ["ID-111", "ID-222"]
longArray = ["ID-111 bis", "ID-222 bis"]

I created them like that because I needed unique IDs in previous steps and now I must use the same color for each pair in the chart I'm drawing them.

My aim is to generate a string with this form:

{
    "ID-111 bis" : chart.color("ID-111"),
    "ID-222 bis" : chart.color("ID-222"),
    ...
}

I tried to do it like this:

 const result = {}
 for(const item of longArray) {
    result[item]=[];
    result[item].push({item : "chart.color(" + shortArray+ ")"});
 }

Which gives me this wrong output:

{
"ID-111 bis" :[{item: "chart.color(ID-111,ID-222)"}],
"ID-222 bis" :[{item: "chart.color(ID-111,ID-222)"}]
}

Any ideas what should I change?

LATER EDIT:

I saw many answers which are pretty similar but there is a condition that must be respected:

The second argument should not be in quotes.

"ID-111 bis" : chart.color("ID-111") - good

"ID-111 bis" : "chart.color("ID-111")" - bad


Solution

  • You need to use the item's value instead of actualValue which seems to be some static value and is not dependent on item in your logic

    And every array item seems to be a new array, which is not what you are looking for

    result[item] = {item : "chart.color(" + item.split(" ")[0] + ")"};
    

    Even more precisely

    var finalValue = {};
    shortArray.forEach( function(s){
       finalValue[s+" bis"] = chart.color(s); //assuming that chart.color is the function you want to invoke
    })