Search code examples
javascriptlodash

How to find a property in a nested object


I'm trying to figure out how to extract result based on an object property value that is inside another object e.g

{
   title: 'The Book',
   author: {
      name: 'Merlin Bridge',
      category: 'Fiction'
   }
}  

Here are my tests:

  // this works
  const test1 = _.find(existingBooks, {
    title: uploadedBooks[i].title,
  });

  // this doesn't work and returns nothing
  const test2 = _.find(existingBooks, {
    'author.name': uploadedBooks[i].author.name,
  });

I want to get the result wherein the author.name is the identifier. Thanks a lot.


Solution

  • As you are using Lodash/Underscore find, I took the liberty to also use the get helper. Please find below an answer which should help you.

    const books = [{
        title: 'The Book',
        author: {
          name: 'Merlin Bridge',
          category: 'Fiction'
        }
      },
      {
        title: 'Another Book',
        author: {
          name: 'Merlin Window',
          category: 'Science'
        }
      }
    ];
    const uploadedBooks = [{
        title: 'Another Book',
        author: {
          name: 'Merlin Window',
          category: 'Science'
        }
      }];
    const i = 0;
    const foundBook = _.find(books, (book, index) => {
      return _.get(book, 'author.name') === _.get(uploadedBooks, [i, 'author', 'name'])
    });
    console.log(foundBook);
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>