如何通过ids数组精确筛选出原始对象数组中的特定元素?

2026-04-02 01:241阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计252个文字,预计阅读时间需要2分钟。

如何通过ids数组精确筛选出原始对象数组中的特定元素?

我有两个数组:数组a:[{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}]; 数组ids:id数组:var ids=[1]; 我想获取数组a中id为1的元素。

Ihavetwoarrays:我有两个数组:arraya:数组:vara[{id:1,

I have two arrays:

我有两个数组:

array a:

数组:

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

array ids:

id数组:

var ids = [1];

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

我想要数组a被数组id过滤,我想要的结果:

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:)

强调解决方案是更好:)

1 个解决方案

#1

4

You can use .filter

如何通过ids数组精确筛选出原始对象数组中的特定元素?

您可以使用.filter

a = a.filter(function(el){ return ~ids.indexOf(el.id)});// should give you [{id: 1, name: 'a'}]
标签:原始

本文共计252个文字,预计阅读时间需要2分钟。

如何通过ids数组精确筛选出原始对象数组中的特定元素?

我有两个数组:数组a:[{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}]; 数组ids:id数组:var ids=[1]; 我想获取数组a中id为1的元素。

Ihavetwoarrays:我有两个数组:arraya:数组:vara[{id:1,

I have two arrays:

我有两个数组:

array a:

数组:

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

array ids:

id数组:

var ids = [1];

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

我想要数组a被数组id过滤,我想要的结果:

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:)

强调解决方案是更好:)

1 个解决方案

#1

4

You can use .filter

如何通过ids数组精确筛选出原始对象数组中的特定元素?

您可以使用.filter

a = a.filter(function(el){ return ~ids.indexOf(el.id)});// should give you [{id: 1, name: 'a'}]
标签:原始