Balasubramanian
Balasubramanian

Reputation: 5510

Find and add extra key in object of array using lodash?

I want to find and add extra key in object of array using lodash. I don't want to do in for loop and maintain in temp data.

"book": [
  {
    "name": "Hulk",
    "series": [
      {
        "name": "mike",
        "id": "100",
      },
      {
        "name": "steve",
        "id": "200"
      }
    ]
  }
],

Need to add detail object inside series array based on name: mike && id:100 search and return the complete book data.

{
  "name": "mike",
  "id": "100",
  "detail":{
    "author": 'apple'
    "year": 1956
  }
},

Upvotes: 0

Views: 676

Answers (1)

Rialgar
Rialgar

Reputation: 753

like this? (note: this modifies the existing object)

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; }

You can replace the arrow syntax with the usual function syntax and use lodash for the forEach and the find to increase compatability with older browser versions.

Upvotes: 1

Related Questions