gpt4 book ai didi

javascript - 扩展数组中的对象而不重新定义

转载 作者:太空宇宙 更新时间:2023-11-04 15:49:28 26 4
gpt4 key购买 nike

我有一个对象数组

var myArray = [{'id':'1','value':'firstValue'},{'id':'1','value':'secondValue'}, etc.]

我希望能够稍后在代码中扩展数组,这样我就可以拥有

var myArray = [{'id':'1','value':'firstValue', 'anothervalue':'anotherFirstValue'},{'id':'1','value':'secondValue', 'anothervalue':'anotherSecondValue'}, etc.]

有没有办法在不重新定义 myArray 的情况下做到这一点?

最佳答案

您可以映射数组,并添加到每个对象:

var myArray = [{
'id': '1',
'value': 'firstValue'
}, {
'id': '1',
'value': 'secondValue'
}];

//later on
myArray = myArray.map(function(obj) {
obj.anothervalue = 'anotherFirstValue';
return obj;
});

console.log(myArray);

关于javascript - 扩展数组中的对象而不重新定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43264039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com