gpt4 book ai didi

javascript - 如何将数组添加到数组对象

转载 作者:行者123 更新时间:2023-12-02 23:14:56 25 4
gpt4 key购买 nike

如何制作object1object2 ?它是来自 API 的 JSON 类型,因此我不能手动将数组的值放入对象中。 Z 实际上是 var z = [4,5,6];一个完全独立的数组。

var object1  = {
value:[{
"x": "apple",
"y": [1,2,3]
}]
};

var object2 = {
value:[{
"x": "apple",
"y": [1,2,3],
"z": [4,5,6]
}]
};

最佳答案

您可以访问数组并更新它:

const updateObjectAtIndex = (arr, index, newData) => {
const clone = [...arr];
const result = {
...clone[index],
...newData
};

clone[index] = result;

return clone;
}

var object1 = {
value:[{
"x": "apple",
"y": [1,2,3]
}]
};

var object2 = {
...object1,
value: updateObjectAtIndex(object1.value, 0, {z: [4, 5, 6]})
}

console.dir(object2)

关于javascript - 如何将数组添加到数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57204736/

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