nip
nip

Reputation: 1697

Filter multiple objects from array

I'm trying to filter an array of objects where the filter is another array (of integers) which are values of properties of the first array. I've managed to make it work but I'm not sure if it's the best way. Since I'm a beginner in javascript, I'd appreciate any suggestions/improvements.

The items.json file contains an object with an array of objects. I want to filter all the objects (within that array) that have an id equal to the "ids" on the itemsids array.

code:

const itemsall = require('./items.json');

let itemsids = [1, 403, 3];

let filtereditems = [];

itemsids.forEach(id => {
  itemsall.items.forEach(item => {
    if (id === item.id) {
      filtereditems.push(item);
    }
  });
});

items.json (a small part of it)

{
    "items": [
        {
            "id": 0,
            "name": "Egg",
            "img": "http://www.serebii.net/pokemongo/items/egg.png"
        },
        {
            "id": 1,
            "name": "Pokeball",
            "img": "http://www.serebii.net/pokemongo/items/20pokeballs.png"
        },
        {
            "id": 2,
            "name": "Greatball",
            "img": "http://www.serebii.net/pokemongo/items/greatball.png"
        }
   ]
}

output: (expected)

[
    {
        "id": 0,
        "name": "Egg",
        "img": "http://www.serebii.net/pokemongo/items/egg.png"
    },
    {
        "id": 403,
        "name": "Cool Incense",
        "img": "http://www.serebii.net/pokemongo/items/incense.png"
    },
    {
        "id": 3,
        "name": "Ultraball",
        "img": "http://www.serebii.net/pokemongo/items/ultraball.png"
    }
]

Thanks!

Upvotes: 4

Views: 11084

Answers (1)

Nenad Vracar
Nenad Vracar

Reputation: 122135

You can use filter() and indexOf() to return filtered array.

var data = {
  "items": [{
    "id": 0,
    "name": "Egg",
    "img": "http://www.serebii.net/pokemongo/items/egg.png"
  }, {
    "id": 1,
    "name": "Pokeball",
    "img": "http://www.serebii.net/pokemongo/items/20pokeballs.png"
  }, {
    "id": 2,
    "name": "Greatball",
    "img": "http://www.serebii.net/pokemongo/items/greatball.png"
  }]
}
let itemsids = [1, 403, 3];

var result = data.items.filter(function(e) {
  return itemsids.indexOf(e.id) != -1
})

console.log(result)

With ES6/ES7 you can use includes() like this.

var result = data.items.filter((e) => itemsids.includes(e.id));

Upvotes: 10

Related Questions