簡體   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