[英]How to add unique objects to json array using javascript in postman
I am trying to add json object to json array, but seems something wrong. 我正在尝试将json对象添加到json数组,但是似乎出了点问题。 what I'm getting array elements as -
我得到的数组元素是什么-
0:{}
local:"con"
name:"con"
order:15
1:{}
local:"con"
name:"con"
order:15
what I'm expecting to happen - 我期望发生的事情-
0:{}
local:"con"
name:"con"
order:15
1:{}
local:"con2"
name:"con2"
order:16
I want points
array should have all unique json objects(with very for loop iteration) but it replaces all previously added json with current json(of current iteration) object and entire array has same json objects at all index positions 我希望
points
组应该具有所有唯一的json对象(非常适合循环迭代),但是它将所有先前添加的json替换为当前json(当前迭代)对象,并且整个数组在所有索引位置都具有相同的json对象
code - 代码-
for(var i = 0; i < machineDetails.length; i++)
{
machine['name'] = machineDetails[i].name;
machine['local'] = machineDetails[i].localName;
machine['order'] = machineDetails[i].orderInLine;
points.push(machine);
console.log(points);
}
in addition to above I tried points[i].push(machine);
除了上述之外,我还尝试了
points[i].push(machine);
but it does not work either and throws error as push property is not defined
. 但是它也不起作用,并且由于
push property is not defined
而引发错误。 Please point me in right direction what i am missing or what should I do? 请向我指出正确的方向,我该丢失什么或该怎么办?
You need to move an assignment of an empty object inside of the loop, to prevent the same object reference, which leads to same values inside. 您需要在循环内移动一个空对象的分配,以防止引用相同的对象,从而导致内部的值相同。
for (var i = 0; i < machineDetails.length; i++) {
machine = {};
or even shorter: 甚至更短:
for (var i = 0; i < machineDetails.length; i++) {
points.push({
name: machineDetails[i].name,
local: machineDetails[i].localName,
order: machineDetails[i].orderInLine
});
}
When using arrays you can use different types of iterations including array.map
which seems to be exactly what you are doing: Mapping the array called machineDetails
to a new one called points
: 使用数组时,可以使用不同类型的迭代,包括
array.map
,这似乎正是您正在做的事情:将名为machineDetails
的数组映射到名为points
的新数组:
const points = machineDetails.map(({ name, localName, orderInLine}) => ({
name,
local: localName,
order: orderInLine,
});
Using map since you are creating a new scope and returning a new object every time the issue in hand which is overriding attributes of an object which you have already referenced it into your array is not going to happen. 使用map是因为您正在创建一个新的作用域,并且每次在覆盖对象的属性的现有问题(已将其引用到数组中的对象)都不会出现时,都会返回一个新对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.