我如何查找并返回特定的对象键,并在lodash中以数组形式返回。
const category = [
{ id: 123, name: "haha"},
{ id: 124, name: "haha2"},
{ id: 125, name: "haha3"},
]
我如何得到这个?结果:[123,124,125]
result = category.map(cat => cat.id)
使每个循环都可以遍历类别,并且类别的每个元素都具有id将其推送到空的arr中
let result = []
const category = [
{ id: 123, name: "haha"},
{ id: 124, name: "haha2"},
{ id: 125, name: "haha3"},
]
category.forEach(c=>{
result.push(c.id)
})
console.log(result)
您可以使用Array.map:
category.map(item => item.id)
const category = [
{ id: 123, name: "haha"},
{ id: 124, name: "haha2"},
{ id: 125, name: "haha3"},
]
const result = category.map(el => el.id);
console.log(result);
您可以这样使用.map
或.reduce
const category = [
{ id: 123, name: "haha"},
{ id: 124, name: "haha2"},
{ id: 125, name: "haha3"},
]
const result = category.reduce((acc, elem)=>{
return [...acc, elem.id];
}, []);
console.log(result);
const result2 = category.map(i=> i.id);
console.log(result2)