繁体   English   中英

如何获取数组中子项的长度

[英]How to get length of sub items in array

我想获得数组company下项目的总长度数,例如在下面的例子中它应该是 5,你知道如何在 java 脚本中做到这一点。 谢谢

这是我的json:

var json ={
        "market": [
            {
                "company": [
                    {
                        "name": "A"
                    },
                    {
                        "name": "B"
                    },
                    {
                        "name": "C"
                    }
                ]
            },
            {
                "company": [
                    {
                        "name": "D"
                    },
                    {
                        "name": "E"
                    }
                ]
            }
        ]
    }
json.market.reduce((acc, market) => acc + market.company.length, 0)

使用 reduce 函数并更新累加器的值

 var json = { "market": [{ "company": [{ "name": "A" }, { "name": "B" }, { "name": "C" } ] }, { "company": [{ "name": "D" }, { "name": "E" } ] } ] } var x = json.market.reduce(function(acc, curr) { // acc mean the accumulator, 0 was passed as the first value acc += curr.company.length; return acc; }, 0) // 0 is the initial value console.log(x)

此代码可能会有所帮助。

var totallength=0;
json.market.reduce(function(i,o){totallength+=o.company.length;},0);
console.log(totallength)

您可以使用Array.prototype.reduce()来获得result

代码:

 const json = { "market": [{ "company": [{ "name": "A" }, { "name": "B" }, { "name": "C" } ] }, { "company": [{ "name": "D" }, { "name": "E" } ] } ] }; const result = json.market.reduce((a, c) => a + c.company.length, 0); console.log(result);

我还在这里发布了一个使用 lodash 的解决方案,有点复杂,但通用. 这意味着它将计算每个属性的总元素:

const data = {
  market: [
    { company: [1, 2, 3], address: [1, 2, 4], test: [6,7]},
    { company: [4, 5, 6], address: [3, 4], bonus: [9] }
  ]
};

// get the length of every array (this can actually be done without lodash with Object.keys(obj).forEach...)
temp = data.market.map(obj => _.mapValues(obj, o => o.length));

counter = {}
temp.forEach(arr => Object.keys(arr).forEach(el => (counter[el] = (counter[el] || 0) + arr[el])))

// counter = { company: 6, address: 5, test: 2, bonus: 1 }

暂无
暂无

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

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