Reputation: 67
I want it to check and then add a book if it doesn't exist. I am having trouble accessing the index('Horror') part.
const bookMap = {
'Horror' => [{
id: 9798721052927,
title: 'Dracula',
author: 'Brahm Stoker'
}],
'Romance' => [{
id: 9798721052927,
title: 'Love Story',
author: 'Brahm Stoker'
}]
}
bookMap.get('Horror').filter(e => e.title === 'Dracula')
Upvotes: 0
Views: 89
Reputation: 1054
As you want to add if that items not available then you can do following
let bookMap = {
'Romance': [{
id: 9798721052927,
title: 'Love Story',
author: 'Brahm Stoker'
}]
};
Object.keys(bookMap).forEach(function(key) {
if (key !== 'Horror') {
bookMap['Horror'] = [{
id: 9798721052927,
title: 'Dracula',
author: 'Brahm Stoker'
}]
}
});
console.log(bookMap)
Upvotes: 1
Reputation: 227230
The =>
for objects is used in PHP, not JavaScript. JavaScript uses :
.
To access the value, you use ['name']
or .name
.
const bookMap = {
'Horror': [{
id: 9798721052927,
title: 'Dracula',
author: 'Brahm Stoker'
}],
'Romance': [{
id: 9798721052927,
title: 'Love Story',
author: 'Brahm Stoker'
}]
};
let books = bookMap.Horror.filter(e => e.title === 'Dracula');
console.log(books);
Upvotes: 1
Reputation: 5234
Your object is not a valid javascript object. The correct way:
const bookMap = {
'Horror': [
{ id: 9798721052927, title: 'Dracula', author: 'Brahm Stoker' }
],
'Romance': [
{ id: 9798721052927, title: 'Love Story', author: 'Brahm Stoker' }
]
}
// then
// access like this
console.log(bookMap.Horror.filter(e => e.title === 'Dracula'))
// or this
console.log(bookMap["Horror"].filter(e => e.title === 'Dracula'))
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1