gpt4 book ai didi

javascript 覆盖添加到数组中的前一个元素

转载 作者:行者123 更新时间:2023-11-28 14:21:34 25 4
gpt4 key购买 nike

当我插入数组时,它会覆盖最后添加的元素。

这是我的代码:

const array = [{ name: [] }];

const test = `result1
result2
result3`;
const ways = test.split(/[\n\r]+/).map(aaa => (aaa));

array.forEach((obj) => {
ways.forEach((element) => {
obj.item = [{ result: element }];
});
});

我得到的输出:

[ 
{
"name": [],
"item": [{ "result": "result3" }]
}
]

我想要的输出:

[
{
"name": [],
"item": [
{ "result": "result1" },
{ "result": "result2" },
{ "result": "result3" }
]
}
]

最佳答案

const array = [{ name: [] }];

const test = `result1
result2
result3`;
const ways = test.split(/[\n\r]+/).map(aaa => (aaa));

array.map((obj) => {
obj.item = [];
ways.map((element) => {
obj.item .push([{ result: element }]);
});
});

console.log(array);

关于javascript 覆盖添加到数组中的前一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55009298/

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