我有一个对象数组,如下例所示:
var b = [
{
'attribute[170]': "41",
'attribute[171]': "15",
'data': 1,
'something': 'some text'
},
{
'attribute[150]': "401",
'attribute[181]': "5",
'test': '1234',
'data': 2.3
}
];
我想在b
中选择包含对象a
var a = {
'attribute[170]': "41",
'attribute[171]': "15"
};
这可能是jQuery.grep
还是映射? (我正在使用jQuery。)
答案 0 :(得分:5)
您可以使用filter
循环浏览b
,并循环浏览a
的属性,查找b
中每个条目的匹配项。提前获取a
属性列表非常有用。
var aprops = Object.keys(a);
var c = b.filter(function(entry) {
return aprops.every(function(key) {
return entry[key] === a[key];
});
});
var b = [
{
'attribute[170]': "41",
'attribute[171]': "15",
'data': 1,
'something': 'some text'
},
{
'attribute[150]': "401",
'attribute[181]': "5",
'test': '1234',
'data': 2.3
}
];
var a = {
'attribute[170]': "41",
'attribute[171]': "15"
};
var aprops = Object.keys(a);
var c = b.filter(function(entry) {
return aprops.every(function(key) {
return entry[key] === a[key];
});
});
console.log(c);
或使用ES2015 +语法:
const aprops = Object.keys(a);
const c = b.filter(entry => aprops.every(key => entry[key] === a[key]));
const b = [
{
'attribute[170]': "41",
'attribute[171]': "15",
'data': 1,
'something': 'some text'
},
{
'attribute[150]': "401",
'attribute[181]': "5",
'test': '1234',
'data': 2.3
}
];
const a = {
'attribute[170]': "41",
'attribute[171]': "15"
};
const aprops = Object.keys(a);
const c = b.filter(entry => aprops.every(key => entry[key] === a[key]));
console.log(c);
它为您提供了一个包含所有匹配对象的数组。如果您只想要第一个匹配的对象而不是数组,那么您将使用find
(在ES2015中添加,即ES6,但很容易进行多边形填充/填充),而不是filter
:
var aprops = Object.keys(a);
var c = b.find(function(entry) {
return aprops.every(function(key) {
return entry[key] === a[key];
});
});
var b = [
{
'attribute[170]': "41",
'attribute[171]': "15",
'data': 1,
'something': 'some text'
},
{
'attribute[150]': "401",
'attribute[181]': "5",
'test': '1234',
'data': 2.3
}
];
var a = {
'attribute[170]': "41",
'attribute[171]': "15"
};
var aprops = Object.keys(a);
var c = b.find(function(entry) {
return aprops.every(function(key) {
return entry[key] === a[key];
});
});
console.log(c);
或使用ES2015 +语法:
const aprops = Object.keys(a);
const c = b.find(entry => aprops.every(key => entry[key] === a[key]));
const b = [
{
'attribute[170]': "41",
'attribute[171]': "15",
'data': 1,
'something': 'some text'
},
{
'attribute[150]': "401",
'attribute[181]': "5",
'test': '1234',
'data': 2.3
}
];
const a = {
'attribute[170]': "41",
'attribute[171]': "15"
};
const aprops = Object.keys(a);
const c = b.find(entry => aprops.every(key => entry[key] === a[key]));
console.log(c);