选择包含对象的数组对象

时间:2017-04-12 09:12:20

标签: javascript arrays

我有一个对象数组,如下例所示:

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。)

1 个答案:

答案 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);