我有这个 JSON 结构:
const arr = [
{
id: "TaskStatuses",
rows: [
{id: "1", name: "Success"},
{id: "2", name: "Error"},
]
},
{
id: "Objects",
rows: [
{id: "1", name: "Object1"},
{id: "2", name: "Object2"},
]
},
{
id: "Groups",
rows: [
{id: "1", name: "Group1"},
{id: "2", name: "Group2"},
]
},
]
我需要创建具有某种条件的数组。如果我的条件正确,我将推送元素 arr.rows。
最后我想得到这个结构:
[
{
Objects: "Object1",
Groups: "Group1"
},
{
Objects: "Object2",
Groups: "Group2"
}
]
我尝试这样做
let sites = []
for (let el in arr) {
if (arr.id == "Objects") {
for (let item of el.rows) {
sites.push({Objects: item.name})
}
}
if (arr.id == "Groups") {
for (let item of el.rows) {
sites.Groups = item.name
}
}
}
答案 0 :(得分:0)
您可以在新对象中映射所需的属性。
const
data = [{ id: "TaskStatuses", rows: [{ id: "1", name: "Success" }, { id: "2", name: "Error" }] }, { id: "Objects", rows: [{ id: "1", name: "Object1" }, { id: "2", name: "Object2" }] }, { id: "Groups", rows: [{ id: "1", name: "Group1" }, { id: "2", name: "Group2" }] }],
ids = ['Objects', 'Groups'],
result = data.reduce((r, { id, rows }) => ids.includes(id)
? rows.map(({ name }, i) => ({ ...r[i], [id]: name }))
: r,
[]
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }