[英]Add new element to each object in array of objects
Suppose I have this:假设我有这个:
var names = [
{
"First": "Jim",
"Last": "Jones"
},
{
"First": "Mike",
"Last": "Smith"
},
{
"First": "Joe",
"Last": "Johnson"
}
]
And I now want to add a "Middle" field with a middle name to each object in that array.我现在想为该数组中的每个对象添加一个带有中间名的“中间”字段。 Can I do it simply?
我可以简单地做吗? Push doesn't seem to exist in this scenario.
在这种情况下似乎不存在推送。
You can just assign it, using obj.Middle
or obj["Middle"]
:您可以使用
obj.Middle
或obj["Middle"]
分配它:
But if you want the ordering to be really the middle one, then it can't, because ES6 property names are ordered first by numbers (as strings) and then by insertion order.但是,如果您希望排序确实是中间的,那么就不能,因为 ES6 属性名称首先按数字(作为字符串)排序,然后按插入顺序排序。
var names = [{ "First": "Jim", "Last": "Jones" }, { "First": "Mike", "Last": "Smith" }, { "First": "Joe", "Last": "Johnson" } ]; names.forEach(obj => obj.Middle = "N/A"); console.log(names);
You can use the .map
method on the Array
object to create a new array without mutating the original array.您可以在
Array
对象上使用.map
方法来创建一个新数组,而无需改变原始数组。
push
adds a new entry to the array and does not update the item. push
向数组添加一个新条目,但不更新该项目。
var names = [{ "First": "Jim", "Last": "Jones" }, { "First": "Mike", "Last": "Smith" }, { "First": "Joe", "Last": "Johnson" } ]; var updatedNames = names.map(name => { const { First, Last } = name; return { First, Last, Middle : 'middle name' } }); console.log(updatedNames);
map method of the javascript can be used to achieve this,可以使用javascript的map方法来实现这一点,
let newNamesArray = names.map(name => {
return {
...name,
"Middle": "The middle name you want"
}
});
names = newNamesArray;
You can also achieve it by using .assign
method of Object
and .map
of Array
this way您也可以通过这种方式使用
Object
.assign
方法和Array
.map
来实现它
var names = [{ "First": "Jim", "Last": "Jones" }, { "First": "Mike", "Last": "Smith" }, { "First": "Joe", "Last": "Johnson" } ]; names = names.map(obj => Object.assign({}, obj, {Middle: "N/A"})); console.log(names);
Note that is very useful if you want to separate the obtained names to the old ones For that, instead of affecting the result to names simply create another variable请注意,如果要将获得的名称与旧名称分开,这非常有用为此,不要将结果影响到名称,只需创建另一个变量
let anotherNames = names.map(obj => Object.assign({}, obj, {Middle: "N/A"}));
As I said the anotherNames and Names variable are totally independent正如我所说的 anotherNames 和 Names 变量是完全独立的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.