Return 使用 Javascript 仅匹配多维数组中多个字符串的对象
Return only the matched objects from multiple strings in a multidimensional array using Javascript
我目前有 2 个数组。一个是包含多个字符串的平面数组,另一个是嵌套数组。我试图 return 我的嵌套数组只包含与我的第一个数组中的字符串匹配的对象。我目前 运行 进入的是我的整个数组正在 returned 如果只有一个匹配项反对匹配的对象。
JS:
const rootIds = ["18828861", "15786287", "13435676"]
const filtData = [
{
year: "2022",
awards: [
{
list: [
{
rootId: "18828861",
name: "Globe",
},
{
rootId: "15786222",
name: "Golden"
},
],
},
],
},
{
year: "2021",
awards: [
{
list: [
{
rootId: "15786223",
name: "Car",
},
{
rootId: "13435676",
name: "Red",
},
],
},
{
list: [
{
rootId: "15786287",
name: "Black",
},
{
rootId: "1578622",
name: "Blue",
},
],
},
],
},
];
const res = rootIds.map((a) => a);
const findIds = filtData.map(obj => obj.awards.filter(( { list }) => list.find(o => rootIds.includes(o.rootId))));
console.log("filtData====", findIds)
期望的输出是:
"filtData====", [[{
list: [{
name: "Globe",
rootId: "18828861"
}]
}], [{
list: [{
name: "Red",
rootId: "13435676"
}]
}, {
list: [{
name: "Black",
rootId: "15786287"
}]
}]]
无法运行演示的 JsFiddle:
https://jsfiddle.net/hb7ej5sg/
在以下位置找到原因:
const findIds = filtData.map(obj => obj.awards.filter(( { list }) => list.find(o => rootIds.includes(o.rootId))));
由于您在 obj.awards
数组上使用 #filter
而不是 #map
并且在 list
上使用 #find
而不是 #filter
,您是从 obj.awards[].list
.
获取整个数组
使用如下正确的方法可以解决问题:
const findIds = filtData.map(obj =>
obj.awards.map(( { list }) =>
list.filter(o => rootIds.includes(o.rootId))
)
);
我目前有 2 个数组。一个是包含多个字符串的平面数组,另一个是嵌套数组。我试图 return 我的嵌套数组只包含与我的第一个数组中的字符串匹配的对象。我目前 运行 进入的是我的整个数组正在 returned 如果只有一个匹配项反对匹配的对象。
JS:
const rootIds = ["18828861", "15786287", "13435676"]
const filtData = [
{
year: "2022",
awards: [
{
list: [
{
rootId: "18828861",
name: "Globe",
},
{
rootId: "15786222",
name: "Golden"
},
],
},
],
},
{
year: "2021",
awards: [
{
list: [
{
rootId: "15786223",
name: "Car",
},
{
rootId: "13435676",
name: "Red",
},
],
},
{
list: [
{
rootId: "15786287",
name: "Black",
},
{
rootId: "1578622",
name: "Blue",
},
],
},
],
},
];
const res = rootIds.map((a) => a);
const findIds = filtData.map(obj => obj.awards.filter(( { list }) => list.find(o => rootIds.includes(o.rootId))));
console.log("filtData====", findIds)
期望的输出是:
"filtData====", [[{
list: [{
name: "Globe",
rootId: "18828861"
}]
}], [{
list: [{
name: "Red",
rootId: "13435676"
}]
}, {
list: [{
name: "Black",
rootId: "15786287"
}]
}]]
无法运行演示的 JsFiddle: https://jsfiddle.net/hb7ej5sg/
在以下位置找到原因:
const findIds = filtData.map(obj => obj.awards.filter(( { list }) => list.find(o => rootIds.includes(o.rootId))));
由于您在 obj.awards
数组上使用 #filter
而不是 #map
并且在 list
上使用 #find
而不是 #filter
,您是从 obj.awards[].list
.
使用如下正确的方法可以解决问题:
const findIds = filtData.map(obj =>
obj.awards.map(( { list }) =>
list.filter(o => rootIds.includes(o.rootId))
)
);