javascript - javascript overwrite previous element added to array
问题描述
When i push into my array, it overwrite the last element added.
Here is my code:
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 }];
});
});
The output i get :
[
{
"name": [],
"item": [{ "result": "result3" }]
}
]
The output i want :
[
{
"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);
推荐阅读
- html - 为 squarespace 封面创建动画背景
- vue.js - vue3 by vite 热替换在宅基地不起作用
- processing - 如何在我的光线投射器中修复扭曲的墙壁?(我尝试过使用余弦校正)
- swift - 如何从一个部分删除一行并同时将其添加到另一个部分?
- javascript - Tampermonkey上是否可以通过JavaScript获取百度OCR访问令牌?
- java - 如何更改 dconf 目录?
- azure-devops - ADO gulp 任务 - 将前一个任务的输出变量作为参数传递
- angular - 如何从角度的rest api响应中提取子对象
- python - python 中的数据扩充错误:TypeError: pic 应该是 PIL Image 或 ndarray。得到
- apache-spark - 使用字典创建函数以将列从字符串更改为整数