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

标签 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... 提前致谢,对语言感到抱歉!!!

最佳答案

我认为这可以帮助你:

获取对象:

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 表达式)。

关于javascript - 在另一个数组中查找数组并获取结果索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46841487/

相关文章:

Typescript:根据对象中子键的存在创建联合类型

javascript - Powershell 单击 javascript 链接

javascript - 在 for 循环中创建对象语法错误

python - 从 numpy 数组中获取给定半径内的值

angular - 在 Angular 中从剪贴板粘贴图像不起作用

javascript - 使用 Webpack 通过 JSON 文件配置 Angular

javascript - Highcharts:更改比例大小

javascript - 点击href时如何接收值

javascript - jQuery 克隆 - 生成的克隆控件不起作用

c++ - 指针值改变C++