[英]How to get all specific values from an array of objects with nested arrays of objects?
I have an array:我有一个数组:
const arr = [
{
name: "name 1",
dontShow: true,
children: [
{
name: "name 2",
key4: 4,
dontShow: false,
children: [],
},
],
},
{
name: "name 3",
dontShow: false,
children: [
{
name: "name 4",
dontShow: true,
children: [
{
name: "name 5",
dontShow: false,
children: null,
},
],
},
],
},
];
I need an array of names from every object, except those that have property dontShow: true
So from that example I would expect such array:我需要来自每个 object 的名称数组,但具有属性
dontShow: true
的名称除外 所以从那个例子中我希望这样的数组:
["name2", "name3", "name5"]
Basically, I need to get a flat array from tree-like structure, lodash/underscore solutions would be also great, I just didn't find them基本上,我需要从树状结构中获得一个平面数组,lodash/underscore 解决方案也很棒,我只是没有找到它们
You can use a recursive function您可以使用递归 function
const arr = [{ name: "name 1", dontShow: true, children: [{ name:"name 2", key4: 4, dontShow: false, children: [], }, ],},{name: "name 3",dontShow: false,children: [{ name: "name 4", dontShow: true, children: [{ name: "name 5", dontShow: false, children: null,},],}, ],},]; let final = (arr, result = []) => { if (Array.isArray(arr)) { arr.forEach(obj => { if (.obj.dontShow) { result.push(obj.name) } if (Array.isArray(obj.children)) { final(obj,children. result) } }) } return result } console.log(final(arr))
You could get a flat array of names with a look to dontShow
.您可以通过查看
dontShow
获得一组平面名称。
const getNames = array => array.flatMap(({ name, dontShow, children }) => [...(dontShow? []: [name]), ...getNames(children || []) ]), array = [{ name: "name 1", dontShow: true, children: [{ name: "name 2", key4: 4, dontShow: false, children: [] }] }, { name: "name 3", dontShow: false, children: [{ name: "name 4", dontShow: true, children: [{ name: "name 5", dontShow: false, children: null, }] }] }], result = getNames(array); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.