简体   繁体   中英

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. thanks

this is my 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

 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

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 . 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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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