在另一个数组中查找数组并获取结果索引

时间:2017-10-20 02:21:22

标签: javascript arrays typescript

我有这个数组:

    var arr = [
{attributes: [{name: "Impregnante", slug: "impregnante", option: "Nessuno"}, {name: "Tegole", slug: "tegole", option: "Senza Tegole"}], id:430, price:"1000"},
{attributes: [{name: "Impregnante", slug: "impregnante", option: "Nessuno"}, {name: "Tegole", slug: "tegole", option: "Rossi"}], id:431, price:"1025"},
{attributes: [{name: "Impregnante", slug: "impregnante", option: "Nessuno"}, {name: "Tegole", slug: "tegole", option: "Verdi"}], id:432, price:"1025"},
{attributes: [{name: "Impregnante", slug: "impregnante", option: "Trasparente"}, {name: "Tegole", slug: "tegole", option: "Senza Tegole"}], id:433, price:"1100"},
{attributes: [{name: "Impregnante", slug: "impregnante", option: "Trasparente"}, {name: "Tegole", slug: "tegole", option: "Rossi"}], id:434, price:"1125"},
{attributes: [{name: "Impregnante", slug: "impregnante", option: "Trasparente"}, {name: "Tegole", slug: "tegole", option: "Verdi"}], id:435, price:"1125"},
{attributes: [{name: "Impregnante", slug: "impregnante", option: "Noce"}, {name: "Tegole", slug: "tegole", option: "Senza Tegole"}], id:436, price:"1100"},
{attributes: [{name: "Impregnante", slug: "impregnante", option: "Noce"}, {name: "Tegole", slug: "tegole", option: "Rossi"}], id:437, price:"1125"},
{attributes: [{name: "Impregnante", slug: "impregnante", option: "Noce"}, {name: "Tegole", slug: "tegole", option: "Verdi"}], id:438, price:"1125"},
{attributes: [{name: "Impregnante", slug: "impregnante", option: "Castagno"}, {name: "Tegole", slug: "tegole", option: "Senza Tegole"}], id:439, price:"1100"},
{attributes: [{name: "Impregnante", slug: "impregnante", option: "Castagno"}, {name: "Tegole", slug: "tegole", option: "Rossi"}], id:440, price:"1125"},
{attributes: [{name: "Impregnante", slug: "impregnante", option: "Castagno"}, {name: "Tegole", slug: "tegole", option: "Verdi"}], id:441, price:"1125"}]

另一个阵列:

var obj =  [{name: "Impregnante", slug: "impregnante", option: "Trasparente"}, {name: "Tegole", slug: "tegole", option: "Rossi"}];

有人可以给我一个建议,如何在arr中找到obj并返回obj所在的id ... Thx提前和对不起语言!!!

2 个答案:

答案 0 :(得分:1)

我认为这可以帮到你:

获取对象:

var arrFilter = arr.filter(function(a, b){ return JSON.stringify(a.attributes) == JSON.stringify(obj) });

// if you need the property ID
arrFilter[0].id

获取索引:

var idx = arr.findIndex(function(a, b){ return JSON.stringify(a.attributes) == JSON.stringify(obj) })

如果需要,可以使用箭头功能(Lambda表达式)。

答案 1 :(得分:0)

请尝试以下操作:

const parseData = (arr, obj) => {
  let found = arr.find(a => JSON.stringify(a.attributes) === JSON.stringify(obj));
  return found ? found.id : null;
}

console.log(parseData(arr, obj)); //434

为了提供浅层对象,我使用了JSON.stringify()。该方法需要严格的操作中涉及的对象的属性顺序。如果不能接受这个要求,你可以用另一种方式实现这种比较。