0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.