我想使用 lodash 在数组对象中找到并添加额外的键。我不想做for循环和维护临时数据。
"book": [
{
"name": "Hulk",
"series": [
{
"name": "mike",
"id": "100",
},
{
"name": "steve",
"id": "200"
}
]
}
],
需要根据detail
搜索在series
数组中添加name: mike && id:100
个对象,并返回完整的book
数据。
{
"name": "mike",
"id": "100",
"detail":{
"author": 'apple'
"year": 1956
}
},
答案 0 :(得分:1)
const list = [
{
"name": "Hulk",
"series": [
{
"name": "mike",
"id": "100",
},
{
"name": "steve",
"id": "200"
}
]
}
];
function addDetail(books, search, detail){
books.forEach(book => {
var entry = book.series.find( item => {
return item.name === search.name && item.id === search.id;
});
if(entry){
entry.detail=detail;
}
})
return books;
}
console.log(addDetail(list, {"name": "mike","id": "100"}, { "author": 'apple', "year": 1956}))
.as-console-wrapper { max-height: 100% !important; top: 0; }
您可以使用通常的函数语法替换箭头语法,并使用lodash作为forEach
和find
,以提高与旧浏览器版本的兼容性。