首页 > 解决方案 > 从对象数组中返回匹配的对象

问题描述

我想根据searchString从给定数组中搜索匹配的值对象。例如,座位字符串将是“对象0”。

var objArray = [
   { id: 0, name: 'Object 0', otherProp: '321', secondVal:'stack' },
   { id: 1, name: 'O1', otherProp: 'Object 0', secondVal: 'Overflow' },
   { id: 2, name: 'Another Object', otherProp: '850', secondVal: 'Context' },
   { id: 3, name: 'Almost There', otherProp: '046', secondVal: 'Object 1' },
   { id: 4, name: 'Last Obj', otherProp: '78', secondVal: 'test' }
];

现在我只想搜索那些具有Object价值的数组。意味着它应该返回我 0,1 & 3 对象

帮助将不胜感激

标签: javascriptarrays

解决方案


您可以使用该array.filter方法和在此过滤器方法中的所有属性上循环来做到这一点。

var objArray = [
   { id: 0, name: 'Object 0', otherProp: '321', secondVal:'stack' },
   { id: 1, name: 'O1', otherProp: 'Object 0', secondVal: 'Overflow' },
   { id: 2, name: 'Another Object', otherProp: '850', secondVal: 'Context' },
   { id: 3, name: 'Almost There', otherProp: '046', secondVal: 'Object 0' },
   { id: 4, name: 'Last Obj', otherProp: '78', secondVal: 'test' }
];

var filteredArray = objArray.filter((obj) => {
  for (var key in obj) {
    if (obj[key] === 'Object 0') {
      return true;
    }
  }
  return false;
});

推荐阅读