从Javascript数组中获取数组数据?

时间:2014-08-30 11:23:38

标签: javascript arrays

我在javascript中有这样的数组:

{id: 'ZM', name: "Zambia"},
{id: 'MZ', name: "Mozambique"},
{id: 'BW', name: "Botswana"},
{id: 'NA', name: "Namibia"},
{id: 'MW', name: "Malawi"},
{id: 'ZW', name: "Zimbabwe"},

如何通过id('',MW)获取perticuler数组记录? 例如。在Fetch之后我想要如下所示的数组记录:

{id: 'BW', name: "Botswana"},
{id: 'MW', name: "Malawi"}

1 个答案:

答案 0 :(得分:1)

你想要这样的东西:

function fetch(array, ids) {
    return array.filter(function (el) {return ids.indexOf(el.id) !== -1;});
}

它返回数组的过滤器版本,其中只包含ids数组中的ID。你可以像这样使用它:

var arr = [ {id: 'ZM', name: "Zambia"},
{id: 'MZ', name: "Mozambique"},
{id: 'BW', name: "Botswana"},
{id: 'NA', name: "Namibia"},
{id: 'MW', name: "Malawi"},
{id: 'ZW', name: "Zimbabwe"}];

function fetch(array, ids) {
    return array.filter(function (el) {return ids.indexOf(el.id) !== -1;});
}

fetch(arr, ["BW","MW"]);//Outputs [{id: 'BW', name: "Botswana"},{id: 'MW', name: "Malawi"}]