通过数组数组映射,查找 id 和更改对象
Map through array of arrays, to find id and change object
我有一个 ID 数组 ['id1', 'id3']
。
我还有一个数组 items
:
[
{
children: [{
children: [{
id: "id1", //This is value I need to find
status: { state: false}, //this is value I need to change
}],
}],
},
{
children: [{
children: [{
id: "id2",
status: { state: false},
}],
}],
},
{
children: [{
children: [{
id: "id3",
status: { state: false},
}],
}],
},
]
我的目标是从第一个数组中通过 id 找到每个 item
,然后更改属性 state
,然后 return 所有 items
包含我已更改的属性。
这是我的尝试,但它再次 return 所有项目,我也不确定如何更改属性。
items.filter(item =>
item.children.map(child =>
child.children.map(object =>
idsArray.map(id => id === object.id)
)))
我认为您可以使用如下递归函数:
let ids = ["id1", "id2"];
let arrayOfItems = [
{
children: [
{
children: [
{
id: "id1",
status: {
state: false
}
}
]
}
]
},
{
children: [
{
children: [
{
id: "id2",
status: {
state: false
}
}
]
}
]
},
{
children: [
{
children: [
{
id: "id3",
status: {
state: false
}
}
]
}
]
}
];
function changeStatus(arrayOfItems, ids) {
return arrayOfItems.map((e) => {
if (e.id && ids.includes(e.id)) {
return { ...e, status: { state: true } };
} else if (e.children) {
return { ...e, children: changeStatus(e.children, ids) };
} else {
return { ...e };
}
});
}
console.log(changeStatus(arrayOfItems,ids));
我有一个 ID 数组 ['id1', 'id3']
。
我还有一个数组 items
:
[
{
children: [{
children: [{
id: "id1", //This is value I need to find
status: { state: false}, //this is value I need to change
}],
}],
},
{
children: [{
children: [{
id: "id2",
status: { state: false},
}],
}],
},
{
children: [{
children: [{
id: "id3",
status: { state: false},
}],
}],
},
]
我的目标是从第一个数组中通过 id 找到每个 item
,然后更改属性 state
,然后 return 所有 items
包含我已更改的属性。
这是我的尝试,但它再次 return 所有项目,我也不确定如何更改属性。
items.filter(item =>
item.children.map(child =>
child.children.map(object =>
idsArray.map(id => id === object.id)
)))
我认为您可以使用如下递归函数:
let ids = ["id1", "id2"];
let arrayOfItems = [
{
children: [
{
children: [
{
id: "id1",
status: {
state: false
}
}
]
}
]
},
{
children: [
{
children: [
{
id: "id2",
status: {
state: false
}
}
]
}
]
},
{
children: [
{
children: [
{
id: "id3",
status: {
state: false
}
}
]
}
]
}
];
function changeStatus(arrayOfItems, ids) {
return arrayOfItems.map((e) => {
if (e.id && ids.includes(e.id)) {
return { ...e, status: { state: true } };
} else if (e.children) {
return { ...e, children: changeStatus(e.children, ids) };
} else {
return { ...e };
}
});
}
console.log(changeStatus(arrayOfItems,ids));