Reality is a Fractal
Reality is a Fractal

Reputation: 67

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

Upvotes: 0

Views: 89

Answers (3)

Abu Sufian
Abu Sufian

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

gen_Eric
gen_Eric

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

ABDULLOKH MUKHAMMADJONOV
ABDULLOKH MUKHAMMADJONOV

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

Related Questions