我有一个对象数组,类似于这个例子:
var b = [
{
'attribute[170]': "41",
'attribute[171]': "15",
'data': 1,
'something': 'some text'
},
{
'attribute[150]': "401",
'attribute[181]': "5",
'test': '1234',
'data': 2.3
}
];
Run Code Online (Sandbox Code Playgroud)
我想从b包含对象属性的数组中选择对象a
var a = {
'attribute[170]': "41",
'attribute[171]': "15"
};
Run Code Online (Sandbox Code Playgroud)
这是可能的,可能jQuery.grep还是映射?(我使用的是jQuery.)
您可以使用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];
});
});
Run Code Online (Sandbox Code Playgroud)
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);Run Code Online (Sandbox Code Playgroud)
或者使用ES2015 +语法:
const aprops = Object.keys(a);
const c = b.filter(entry => aprops.every(key => entry[key] === a[key]));
Run Code Online (Sandbox Code Playgroud)
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);Run Code Online (Sandbox Code Playgroud)
这为您提供了一个包含所有匹配对象的数组.如果你只想要第一个匹配的对象,而不是数组,你可以使用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];
});
});
Run Code Online (Sandbox Code Playgroud)
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);Run Code Online (Sandbox Code Playgroud)
或者使用ES2015 +语法:
const aprops = Object.keys(a);
const c = b.find(entry => aprops.every(key => entry[key] === a[key]));
Run Code Online (Sandbox Code Playgroud)
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);Run Code Online (Sandbox Code Playgroud)