gpt4 book ai didi

javascript - 如何从对象数组中的对象数组中搜索值?

转载 作者:行者123 更新时间:2023-12-03 07:03:07 25 4
gpt4 key购买 nike

我有一个对象数组,其中每个对象都有一个对象的内部数组,而对象的内部数组又有一个对象的内部数组,它可以转到我想要过滤和显示的内部对象的任何级别。

obj = [{ name: "apple", subGroups:  [{ name: "apple-a", subGroups: { name: "apple-b", subGroups:  [{ name: "apple-c", subGroups: { name: "apple-d", subGroups:[]}}]}}]}
{ name: "orange", subGroups: [{ name: "orange-a", subGroups: { name: "orange-b", subGroups: [{ name: "orange-c", subGroups: { name: "orange-d", subGroups:[]}}]}}]}
{ name: "mango", subGroups: [{ name: "123", subGroups: []}]}
{ name: "grapes", subGroups: [{ name: "123", subGroups: []}]}
{ name: "pear", subGroups: [{ name: "123", subGroups: []}]}]

searchvalue 是动态的 'orange-d' ,

searchvalue = 'orange-d';
result = { name: "orange-d", subGroups:[]}

const newArr = obj.map(obj => {
return obj.name === searchvalue;
}).flat();

我试过过滤器、 map 、平面但我找不到输出,请帮助

最佳答案

你可以拿Array#flatMap之前检查移交的数组或对象,就像稍后作为 subGroups 一样。

const
find = (array, name) => (Array.isArray(array) ? array : [array])
.flatMap(o => o.name === name ? o : find(o.subGroups, name)),
data = [{ name: "apple", subGroups: [{ name: "apple-a", subGroups: { name: "apple-b", subGroups: [{ name: "apple-c", subGroups: { name: "apple-d", subGroups: [] } }] } }] }, { name: "orange", subGroups: [{ name: "orange-a", subGroups: { name: "orange-b", subGroups: [{ name: "orange-c", subGroups: { name: "orange-d", subGroups: [] } }] } }] }, { name: "mango", subGroups: [{ name: "123", subGroups: [] }] }, { name: "grapes", subGroups: [{ name: "123", subGroups: [] }] }, { name: "pear", subGroups: [{ name: "123", subGroups: [] }] }],
result = find(data, 'orange-d');

console.log(result);

关于javascript - 如何从对象数组中的对象数组中搜索值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64125324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com