我创建了一个过滤器来从数组中检索对象。使用了一些对象值,但现在我想将 ids 作为数组而不是单独使用。我知道在这种情况下推送是不正确的,并且由于我仍在过滤器内,请问我该如何实现这一点?
arrayList = [
{
id: 48589,
height: 5.8,
active: false
},
{
id: 84697,
height: 4.6,
active: true
},
{
id: 887697,
height: 5.0,
active: true
}
]
arrayList.filter(c => {
if(c.active){
//`I used the other values here
} else {
//Now I need c.id as an array to search my db
ids = [];
ids.push(c.id)
}
})
最佳答案
您需要格式化您的数组。然后使用map()
从现有数组创建一个新数组:
var arrayList = [
{
id: 48589,
height: 5.8
},
{
id: 84697,
height: 4.6
}
]
var ids = arrayList.map(c => c.id);
console.log(ids);
根据问题中的更新,您可以尝试 forEach()
并且您还在外部声明了 ids
:
var arrayList = [
{
id: 48589,
height: 5.8,
active: false
},
{
id: 84697,
height: 4.6,
active: true
},
{
id: 887697,
height: 5.0,
active: true
}
]
var ids = [];
arrayList.forEach(c => {
if(c.active){
//`I used the other values here
} else {
//Now I need c.id as an array to search my db
ids.push(c.id)
}
});
console.log(ids);
关于javascript - 从循环值创建一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50633737/