How to find if a specific key is true in Array of objects

Viewed 89

I have this array and I want to to get a boolean(true) if there is a 'three' that is equal to 9

myArr = [ { apple: 6, basket: [ { one: 1, two: 2, three: 3 }, { one: 4, two: 5, three: 6 } ] }, { apple: 9, basket: [ { one: 1, two: 2, three: 3 }, { one: 4, two: 5, three: 9 } ] } ]

What I tried:

enter code here

this.myArr.forEach( data => {
      if(data.basket.filter(cur => cur.one === 0 || cur.three === 9)) {
       console.log('true')
      }
    })

This always logs true for some reason I don't know why.

2 Answers

.filter will always return an array of elements which pass the test, and arrays are truthy. Even if no elements pass the test, the array will still be truthy:

const arr = [1, 2, 3].filter(() => false);
if (arr) {
  console.log('truthy');
}

Use .some instead, to see if there is at least one element which passes the test:

const myArr = [{
  apple: 6,
  basket: [{
    one: 1,
    two: 2,
    three: 3
  }, {
    one: 4,
    two: 5,
    three: 6
  }]
}, {
  apple: 9,
  basket: [{
    one: 1,
    two: 2,
    three: 3
  }, {
    one: 4,
    two: 5,
    three: 9
  }]
}]

myArr.forEach(data => {
  if (data.basket.some(cur => cur.one === 0 || cur.three === 9)) {
    console.log('true');
  }
});

filter returns to array and use find which will return matched item or null when no match.

In you code, Just change from filter to find will work fine.

const myArr = [
  {
    apple: 6,
    basket: [
      { one: 1, two: 2, three: 3 },
      { one: 4, two: 5, three: 6 }
    ]
  },
  {
    apple: 9,
    basket: [
      { one: 1, two: 2, three: 3 },
      { one: 4, two: 5, three: 9 }
    ]
  }
];

const items = myArr.map(data =>
  data.basket.find(cur => cur.one === 0 || cur.three === 9) ? "true" : "false"
);

console.log(items);

Related