计算嵌套对象数

const json = [{

  "order": 1111,

  "items": [

    {

      "colour1": "red",

      "colour2": "yellow",

    },

    {

      "colour1": "red",

      "colour2": "red",

    },

    {

      "colour1": "red",

      "colour2": "red",

    }

  ]

},

{

  "order": 2222,

  "items": [

    {

      "colour1": "black",

      "colour2": "blue",

      "colour3": "orange"

    },

    {

      "colour1": "white",

      "colour2": "red",

      "colour3": "green",

      

    }

  ]

}]


Object.entries(json).forEach(([i, v]) => {

    let count = [];

    Object.entries(v.items).forEach(([j, k]) => {

        if (k.colour2.includes('red')) {

            count.push(k.colour2)

        }

    });

    console.log(count, count.length) //length = [2, 1]

});


我觉得我写的这段代码不是过滤和计算长度的有效方法。目标是过滤某个值并得到结果。寻找替代方法和正确的 es6 方法来做到这一点。谢谢


鸿蒙传说
浏览 95回答 3
3回答

幕布斯6054654

使用reduce()const json = [{"order":1111,"items":[{"colour1":"red","colour2":"yellow"},{"colour1":"red","colour2":"red"},{"colour1":"red","colour2":"red"}]},{"order":2222,"items":[{"colour1":"black","colour2":"blue","colour3":"orange"},{"colour1":"white","colour2":"red","colour3":"green"}]}]const res = json.reduce((acc, order) => {  let red = order.items.filter(color => color.colour2 === 'red')  return red.length ? [...acc, red.length] : acc}, [])console.log(res)注意:要获得过滤后的结果而不是计数返回[...acc, red]

潇湘沐

将有多种方法解决此问题,但如果您只对出现“colour2”:“red”感兴趣。您也可以使用类似的东西。 let json = [{"order":1111,"items":[{"colour1":"red","colour2":"yellow"},{"colour1":"red","colour2":"red"},{"colour1":"red","colour2":"red"}]},{"order":2222,"items":[{"colour1":"black","colour2":"blue","colour3":"orange"},{"colour1":"white","colour2":"red","colour3":"green"}]}]   let count=[];    for(let i of json){    count.push(JSON.stringify(i).match(/"colour2":"red"/g).length)    }console.log(count);

烙印99

也许这里的效率不是最好的,但它是可以理解的代码:let count = [];json.forEach((order, index) => {  count[index] = [];  order.items.forEach((item) => {    if (item.colour2 === "red") {      count[index].push(item.colour2);    }  });});console.log(count);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript