olo
olo

Reputation: 5271

Count nested object numbers

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

I feel like this code I wrote isn't an efficient way to filter and count length. The goal is to filter a certain value and get the result. Looking for an alternative way and proper es6 way to do it. Thanks

Upvotes: 0

Views: 61

Answers (3)

Anand
Anand

Reputation: 408

There will be multiple approaches to this problem but if you are only interested in getting occurrences of "colour2": "red". You can use something like this also.

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

Upvotes: 1

User863
User863

Reputation: 20039

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

Note: To get a filtered result instead of count return [...acc, red]

Upvotes: 1

Yevhenii Shlapak
Yevhenii Shlapak

Reputation: 786

Maybe not the best efficiency here, but it is understandable code:

let count = [];
json.forEach((order, index) => {
  count[index] = [];
  order.items.forEach((item) => {
    if (item.colour2 === "red") {
      count[index].push(item.colour2);
    }
  });
});
console.log(count);

Upvotes: 0

Related Questions