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

时间:2018-05-15 15:28:06

标签: javascript

我想得到数组company下项目的总长度数量,例如在下面的示例中它应该是5,您是否知道如何在java脚本中执行此操作。感谢

这是我的json:

var json ={
        "market": [
            {
                "company": [
                    {
                        "name": "A"
                    },
                    {
                        "name": "B"
                    },
                    {
                        "name": "C"
                    }
                ]
            },
            {
                "company": [
                    {
                        "name": "D"
                    },
                    {
                        "name": "E"
                    }
                ]
            }
        ]
    }

5 个答案:

答案 0 :(得分:1)

-s00

答案 1 :(得分: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)

答案 2 :(得分:0)

此代码可能会有所帮助。

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

答案 3 :(得分:0)

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

代码:



const json = {market: [{company: [{name: 'A',company2: [{name: 'AA'},{name: 'BB'},{name: 'CC'}]},{name: 'B'},{name: 'C'}]},{company: [{name: 'D'},{name: 'E',company2: [{name: 'AAA'},{name: 'BBB'},{name: 'CCC'}]}]}]};
const result = json.market.reduce((a, c) => a += c.company.length + c.company.reduce((aa, cc) => cc.company2 ? a += cc.company2.length : 0, 0), 0);

console.log(result);




答案 4 :(得分:0)

我还在这里发布了一个使用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 }