javascript - 遍历对象并插入元素
问题描述
假设我有这个:
const data = [
{
table: [
[{
textValue: 'One'
},
{
textValue: 'Two',
rows: 3
},
{
textValue: 'Three',
rows: 3
},
{
textValue: 'Four'
}],
[{
textValue: 'RED',
rows: 2
},
{
textValue: 'GREEN'
},
{
textValue: 'BLUE',
rows: 1
}]
]
}
];
我要追求的是它遍历对象的位置(Object.entries()
会工作吗?)并看到它rows
存在并插入X
许多空''
字符串,所以你会有类似的东西:
const data = [
{
table: [
[{
textValue: 'One'
},
{
textValue: 'Two',
rows: 3
},
'',
'',
'',
{
textValue: 'Three',
rows: 3
},
'',
'',
'',
{
textValue: 'Four'
}],
[{
textValue: 'RED',
rows: 2
},
'',
'',
{
textValue: 'GREEN'
},
{
textValue: 'BLUE',
rows: 1
},
''
]
]
}
];
我考虑过使用 afor in
但是当需要推送元素时我不知道要编辑它的父对象。
解决方案
您可以使用.map()
and which 将根据给定对象.flatMap()
的数量返回插入的字符串字符数组,该数组将被展平为结果数组:rows
const data = [{ table: [ [{ textValue: 'One' }, { textValue: 'Two', rows: 3 }, { textValue: 'Three', rows: 3 }, { textValue: 'Four' } ], [{ textValue: 'RED', rows: 2 }, { textValue: 'GREEN' }, { textValue: 'BLUE', rows: 1 } ] ] }];
const result = data.map(obj => ({
...obj,
table: obj.table.map(arr =>
arr.flatMap((iobj) => [iobj, ...Array(iobj.rows || 0).fill('')])
)
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important;} /* ignore */
推荐阅读
- sql-server - SQL Server 并发用户限制 1 - 锁定
- angular - 材料单选按钮内的角度材料表单字段不会触发单选按钮
- node.js - 如何从在 AWS ecs 上使用 docker 部署的应用程序获取日志
- sql - 如果为空则插入数据
- python - 使用 python3 将值插入 SQLite3 DB 表时出错
- linux - 我在 Linux 中的 Windows 文件夹在哪里?
- android - 使用 API 注册后,真实 android 设备中的网络请求失败错误
- java - 在 IntelliJ 2018.1 的编辑器中显示所选类名的源代码
- python - 如何在python中的while循环结束时打印所有输出
- c# - Winform无法添加elementHost