简体   繁体   中英

How do I check if a Map of Strings to Arrays of Objects has a given value within the Object?

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')

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM