简体   繁体   English

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

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

I want to get the total length number of items under array company for example in below example it should be 5, do you have an idea how to do it in java script.我想获得数组company下项目的总长度数,例如在下面的例子中它应该是 5,你知道如何在 java 脚本中做到这一点。 thanks谢谢

this is my json:这是我的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)

Use reduce function and update the value of the accumulator使用 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)

this code may be helpful.此代码可能会有所帮助。

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

You can use Array.prototype.reduce() to get the result您可以使用Array.prototype.reduce()来获得result

Code:代码:

 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);

I'm also posting here a solution using lodash, a bit more complicated, but generic .我还在这里发布了一个使用 lodash 的解决方案,有点复杂,但通用. Which means it's gonna count the total elements of every property:这意味着它将计算每个属性的总元素:

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