Gover123
Gover123

Reputation: 69

How to show object from array which includes current key?

I have an array with many objects like this:

        "title": "Harry Potter and the Philosophers Stone",
        "price": "7.99",
        "image": "https://say-hi.me/wp-content/uploads/2015/12/Digital-Harry-Potter-1.jpg",
        "id": 1,
        "author": "J.K.Rowling",
        "rating": 5,
        "onTop": false

Some of these objects have onTop key with value true. So how i can show objects using method map ONLY with value true ?

Upvotes: 0

Views: 73

Answers (2)

Mister Jojo
Mister Jojo

Reputation: 22265

that ?

const data = 
  [ { title:  'Harry Potter and the Philosophers Stone'
    , price:  '7.99'
    , image:  'https://say-hi.me/wp-content/uploads/2015/12/Digital-Harry-Potter-1.jpg'
    , id:     1
    , author: 'J.K.Rowling'
    , rating: 5
    , onTop:  false
    }
  , { title:  'xyz'
    , price:  '7.99'
    , image:  'https://xyz.jpg'
    , id:     1
    , author: 'xyz'
    , rating: 5
    , onTop:  true
    }
  ]

const res = data.filter(e=>e.onTop)

console.log( res )
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Jeff
Jeff

Reputation: 660

You can use the lodash library here https://lodash.com/docs/4.17.15#filter

Then you can do

var books = [
  { 'title': 'doggo', 'onTop': true },
  { 'title': 'catto', 'onTop': false }
];
 
const onTopBooks = _.filter(books, function(o) { return o.onTop; });

which should return you a new array with

[{ title: 'doggo', onTop: true }]

I would not use the map method because it returns a value for each element in the array and you would need an additional loop to remove the null items you dont want. filter or some method similar like select will be better here.

Additionally, you could just do something even more basic like:

let onTopBooks = []

books.forEach( book => {
  if (book.onTop) {
    onTopBooks.push(book) 
  }
})

return onTopBooks

Upvotes: 0

Related Questions