按ID数组过滤原始对象数组 [英] Filter the original array of objects by array of ids

查看:60
本文介绍了按ID数组过滤原始对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:

数组a:

var a = [
  {
    id: 1,
    name: 'a'
  },
  {
    id: 2,
    name: 'b'
  },
  {
    id: 3,
    name: 'c'
  }
];

数组ID:

var ids = [1];

我想通过数组ID过滤数组,我想要的结果:

I want to array a filtered by array ids, result i wanted:

var a = [
  {
    id: 1,
    name: 'a'
  }
];

最重要的是我想要对原始数组进行更改,而不是返回一个新数组。

The most important thing is i want the change on the original array, rather than return a new array.

下划线解决方案更好:)

underscore solution is better:)

推荐答案

你可以用< a href =https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\"rel =nofollow>。过滤

a = a.filter(function(el){ 
    return ~ids.indexOf(el.id)
});

// should give you [{id: 1, name: 'a'}]

这篇关于按ID数组过滤原始对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆