使用lodash在数组对象中查找并添加额外的键?

时间:2018-05-25 12:14:11

标签: javascript arrays filter lodash

我想使用 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
  }
},

1 个答案:

答案 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作为forEachfind,以提高与旧浏览器版本的兼容性。