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

我有上面的对象,它内有对象数组,我试图检查'六月',有没有is_new,但失败?迭代使用对象键和findIndex失败

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

的可能的复制[迭代通过对象属性(https://stackoverflow.com/questions/8312459/iterate-through-object-properties) – Michelangelo

+0

你忘了一个逗号在'name'属性之后。你也可以在'updated_at'后面删除逗号。 – Chris

+2

而不是使用'findIndex(...)> -1',你应该做一些(...)' – Bergi

回答

0

如果你想测试是否有任何六月数组中的项目已经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只是运行对每个元素的功能在一个数组中。

.some如果它应用的任何函数返回true,则返回true。

+0

有的只是返回true或false吧?比较类似于过滤器,只是过滤器返回数组,我是吗? –

+0

是的,这是正确的。参见[Array.prototype.some](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some) –

-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