Home > Net >  Add key and value to an array using javascript
Add key and value to an array using javascript

Time:12-09

I have two objects and I need to create one new array with a new structure for example: These are my objects:

Object 1: [{ "Question":"Climate change", "Total":"3.456" }]

Object 2: [{ "Question":"Climate change", "Total":"3.567" }]

I need this Output

[{ "x":3.456, "y":3.567 }]

I tried creating the array I need with one of the arrays... So I used the first array to have: [{y:3.456}] and it works, now I need to add the x key and the value from the second array so I tried this:

Where chardatavalue is one of the arrays(which contains the "y" key and the value) and arrayforxls2 is the other one, but the code I have only assign the last value of the seconf array to all of the "x" keys.

var resultnew = chartdatavalue.map(function (el) {
 var o = Object.assign({}, el);

     for (let i of arrayforxls2) {
         
         o.x = i.Total;
                
      }
      return o;
    });

chartdatavalue has this structure:

[{
y: '3.893'
}]

arrayxls2 has this structure:

[{
"Question":"Climate change",
"Total":"3.567"
}]

I need this output:

[{ "x":3.567, "y":3.893 }] Can you please help me.

CodePudding user response:

Possibly you are looking for this:

var resultnew = chartdatavalue.map(function (el, i) {
    return Object.assign({ x: arrayforxls2[i].Total }, el);
});

The change here is that i is captured and used, so that the ith object from the one array is merged with the ith of the other.

You can also use object spread syntax instead of Object.assign for this:

var resultnew = chartdatavalue.map((el, i) =>
    ({ x: arrayforxls2[i].Total, ...el})
);

Or, when there are other properties in el that you need to ignore, then with object destructuring:

var resultnew = chartdatavalue.map(({y}, i) =>
    ({ x: arrayforxls2[i].Total, y})
);

CodePudding user response:

Something like this:

var resultnew = chartdatavalue.map((el, i) => ({x: el.Total, y: arrayforxls2[i].Total}));

This iterates over one of the arrays, and uses the index i to get the value from the corresponding object in the other array.

There's no point in using Object.assign() since the result objects don't include any of the property names of the input objects.

  • Related