Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 756
nip Avatar asked Oct 26 '25 23:10

nip


1 Answers

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));
like image 193
Nenad Vracar Avatar answered Oct 28 '25 12:10

Nenad Vracar