-1
{
  "June": [
    {
      "id": "59361b2fa413468484fc41d29d5",      
      "is_new": false,
      "name":"John"
      "updated_at": "2017-06-07 10:52:05",
    }
  ]
}

I have above object and within it it has array of object, I tried to check within 'June', is there any is_new, but failed?

const has_any_is_new = Object.keys(arr).map(obj => 
    arr[obj].map(obj2 => obj2.findIndex(o => o.is_new) > -1)
);
Alan Jenshen
  • 3,159
  • 9
  • 22
  • 35

2 Answers2

0

If you want to test whether any of the items in the June array has is_new==true, you can use .some:

let months = {
  "June" : [
    {
      "id": "59361b2fa413468484fc41d29d5",      
      "is_new": false,
      "name":"John",
      "updated_at": "2017-06-07 10:52:05",
    },
     {
      "id": "59361b2fa413468484fc41d29d6",      
      "is_new": true,
      "name":"John2",
      "updated_at": "2017-06-07 10:52:05",
    }
  ]
}

const has_any_is_new = Object.keys(months).some( month => 
    months[month].some( obj => obj.is_new )
);

console.log(has_any_is_new)

.map just runs a function against each element in an array.

.some returns true if any of the functions it applies returns true.

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • some is just return true or false right? the comparison is similar to filter, just that filter return the array, am I right? – Alan Jenshen Jun 08 '17 at 03:16
  • Yep that's correct. See [Array.prototype.some](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some) – Jeremy Thille Jun 08 '17 at 06:52
-1

You have one map too much. arr[obj] already refers to the "June" array of objects, so obj2 has the .is_new property but no map method. Use

const obj = { "June": […] };
const news = Object.keys(obj).map(key => 
    [key, obj[key].some(o => o.is_new)]
); // an array of month-boolean-tuples

or

const has_any_is_new = Object.keys(obj).some(key => 
    obj[key].some(o => o.is_new)
); // a boolean whether any month has a new entry
Bergi
  • 630,263
  • 148
  • 957
  • 1,375