简体   繁体   English

从数组中过滤多个对象

[英]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. 由于我是javascript的初学者,我很感激任何建议/改进。

The items.json file contains an object with an array of objects. items.json文件包含一个带有对象数组的对象。 I want to filter all the objects (within that array) that have an id equal to the "ids" on the itemsids array. 我想过滤所有对象(在该数组中),其id等于itemsids数组上的“ids”。

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.json(其中的一小部分)

{
    "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! 谢谢!

You can use filter() and indexOf() to return filtered array. 您可以使用filter()indexOf()返回已过滤的数组。

 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. 使用ES6 / ES7,你可以像这样使用includes()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM