简体   繁体   English

查找嵌套数组的 object 子项的长度

[英]Find length of a nested array's object children

I have a JavaScript object.我有一个 JavaScript object。 Is there a built-in or accepted best practice way to get the length of all the children, here in this case for the first object in array it should be one and for the second object two, and the total comes down to 3.是否有内置或公认的最佳实践方法来获取所有孩子的长度,在这种情况下,数组中的第一个 object 应该是一个,第二个 object 应该是两个,总数下降到 3。

const testData = [
    {
        account: "A",
        children: [
            {
                account: "Test",
                children: [],
            },
        ],
    }, {
        account: "B",
        children: [
            {
                account: "Test1",
                children: [],
            },
            {
                account: "Test2",
                children: [],
            },
        ],
    },

]

The recursive solution, should you need it递归解决方案,如果你需要它

 const testData = [ { account: "A", children: [ { account: "Test", children: [{account:"Test-Grandchild", children:[{account:"Test-Great-Grandchild", children:[]}]}], }, ], }, { account: "B", children: [ { account: "Test1", children: [], }, { account: "Test2", children: [], }, ], }, ] const countChildren = obj => obj.children.length + obj.children.reduce((acc,c) => acc + countChildren(c), 0 ); const result = testData.reduce ( (acc,c) => acc + countChildren(c),0) console.log(result);

Sure, Array.reduce当然, Array.reduce

 const nOfTestDataChildren = [ { account: "A", children: [ { account: "Test", children: [], }, ], }, { account: "B", children: [ { account: "Test1", children: [], }, { account: "Test2", children: [], }, ], }, ].reduce( (acc, val) => acc + val.children.length, 0); console.log(nOfTestDataChildren);

I think Kooilnic 's answer perfect for the situation since we are reducing the array into a single number value and it should be accepted as the actual answer.我认为Kooilnic的答案非常适合这种情况,因为我们正在将数组减少为单个数值,并且应该将其作为实际答案接受。 But I want to propose another solution using Array.forEach :但我想使用Array.forEach提出另一种解决方案:

 const testData = [ { account: "A", children: [ { account: "Test", children: [], }, ], }, { account: "B", children: [ { account: "Test1", children: [], }, { account: "Test2", children: [], }, ], }, ] let numberOfChildren = 0 testData.forEach(datum => numberOfChildren += datum.children.length) console.log({ numberOfChildren })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM