0

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')
1
  • I would recommend you to use a Map instead of an object Commented Oct 29, 2021 at 20:51

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.