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.
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.
5 Answers
Reset to default 3As 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/npm/[email protected]/lodash.min.js"></script>
You can Use below code to iterate your json object.
var myObj = {
title: 'The Book',
author: {
name: 'Merlin Bridge',
category: 'Fiction'
}
}
Object.keys(myObj).forEach(key => {
console.log(JSON.stringify(myObj[key]));
});
It's possible to add dynamically named properties to JavaScript objects.
Assuming you are looping an array and not an object:
var a = _.map(existingBooksArray, function(existingBook) {
return {[existingBook.author.name]: existingBook.title}
});
Result of a:
[
{
Merlin Bridge: "The Book"
}
]
use .key method
Object.keys(myObj).forEach(key => {
console.log(myObj[key]);});
var myObj = {
title: 'The Book',
author: {
name: 'Merlin Bridge',
category: 'Fiction'
}
}
Object.keys(myObj).forEach(key => {
console.log(JSON.stringify(myObj[key]));
});
var myObj = {
title: 'The Book',
author: {
name: 'Merlin Bridge',
category: 'Fiction'
}
}
Object.keys(myObj).forEach(key => {
console.log(JSON.stringify(myObj[key]));
});