[英]Add key and value to an array using javascript
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 1:[{“问题”:“气候变化”,“总计”:“3.456”}]
Object 2: [{ "Question":"Climate change", "Total":"3.567" }] Object 2:[{“问题”:“气候变化”,“总计”:“3.567”}]
I need this Output我需要这个 Output
[{ "x":3.456, "y":3.567 }] [{ "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:我尝试使用 arrays 之一创建我需要的数组...所以我使用第一个数组拥有: [{y:3.456}] 并且它有效,现在我需要添加 x 键和第二个数组中的值所以我尝试了这个:
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.其中 chardatavalue 是数组之一(其中包含“y”键和值),而 arrayforxls2 是另一个,但我仅将 seconf 数组的最后一个值分配给所有“x”键的代码。
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: chartdatavalue 具有以下结构:
[{
y: '3.893'
}]
arrayxls2 has this structure: arrayxls2 具有以下结构:
[{
"Question":"Climate change",
"Total":"3.567"
}]
I need this output:我需要这个 output:
[{ "x":3.567, "y":3.893 }] Can you please help me. [{ "x":3.567, "y":3.893 }] 你能帮帮我吗?
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 i th object from the one array is merged with the i th of the other.这里的变化是
i
被捕获并使用,因此一个数组中的第 i个object 与另一个数组的第 i个合并。
You can also use object spread syntax instead of Object.assign
for this:您还可以为此使用 object 扩展语法而不是
Object.assign
:
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:或者,当您需要忽略
el
中的其他属性时,使用 object 解构:
var resultnew = chartdatavalue.map(({y}, i) =>
({ x: arrayforxls2[i].Total, y})
);
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.这将迭代其中一个 arrays,并使用索引
i
从另一个数组中的相应 object 中获取值。
There's no point in using Object.assign()
since the result objects don't include any of the property names of the input objects.使用
Object.assign()
毫无意义,因为结果对象不包含输入对象的任何属性名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.