使用Object键迭代并且findIndex失败

时间:2017-06-07 11:03:04

标签: javascript reactjs ecmascript-6

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

我有上面的对象,并且在其中有一个对象数组,我试图检查六月',是否有任何is_new,但是失败了?

const has_any_is_new = Object.keys(arr).map(obj => 
    arr[obj].map(obj2 => obj2.findIndex(o => o.is_new) > -1)
);

2 个答案:

答案 0 :(得分:0)

如果您想测试June数组中的任何项目是否is_new==true,您可以使用.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只针对数组中的每个元素运行一个函数。

如果应用的任何函数返回true,则

.some返回true。

答案 1 :(得分:-1)

你有一个map太多了。 arr[obj]已经引用了“六月”对象数组,因此obj2具有.is_new属性但没有map方法。使用

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

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