Javascript过滤数组从另一个数据

Javascript过滤数组从另一个数据

本文介绍了Javascript过滤数组从另一个数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组对象:

  [
{id:1,name:'Pedro'},
{id:2,name:'Miko'},
{id:3,name:'Bear'},
{id:4,name:'Teddy'},
{id:5,name:'Mouse'}
]

与ids [1,3,5]



如何过滤数组对象留下记录只有从第二个ID?
Thanks!

解决方案

试试这个(
$ $ $ $ $ $ $ $ $ var array = [
{id: 1,name:'Pedro'},
{id:2,name:'Miko'},
{id:3,name:'Bear'},
{id:4, name:'Teddy'},
{id:5,name:'Mouse'}
];

var filterArray = [1,3,5];

var filtered = array.filter(function(item){
return filterArray.indexOf(item.id)!== -1;
});


I have an array object:

[
    { id:1, name: 'Pedro'},
    { id:2, name: 'Miko'},
    { id:3, name: 'Bear'},
    { id:4, name: 'Teddy'},
    { id:5, name: 'Mouse'}
]

and have array with ids [1,3,5]

How to filter array object to leave records only with id's from second one?Thanks!

Try this (fiddle):

var array = [
    { id:1, name: 'Pedro'},
    { id:2, name: 'Miko'},
    { id:3, name: 'Bear'},
    { id:4, name: 'Teddy'},
    { id:5, name: 'Mouse'}
];

var filterArray = [1,3,5];

var filtered = array.filter(function(item) {
    return filterArray.indexOf(item.id) !== -1;
});

这篇关于Javascript过滤数组从另一个数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:32