搜索Javascript对象数组

时间:2018-01-13 07:33:57

标签: javascript

我正在尝试按字符串过滤javascript对象数组。但我希望过滤器查看每个属性并测试它以查看字符串是否有效。 AngularJS有一个内置的过滤器可以做到这一点,但我找不到任何解决方案。

[
    {
        "title":"Mr.",
        "name":"John Smith",
        "firstName":"John",
        "lastName":"Smith"
    },
    {
        "title":"Mr.",
        "name":"Bill Smith",
        "firstName":"Bill",
        "lastName":"SMith"
    }

]

因此,例如,如果我为文本字符串输入'Jo',它将在索引0处返回对象,如果您只想搜索单个属性,这很容易做到。

现在,如果我输入'Mr',它应该在索引0和索引1处带回两个项目,因为我们正在搜索所有属性。

希望这对我所要求的内容有意义。

编辑:非常抱歉昨晚是深夜,我在数据结构中留下了非常重要的细节。

{
        "title":"Mr.",
        "name":"John Smith",
        "firstName":"John",
        "lastName":"Smith",
        "contactType":{
            "name":"test"
        },
        "addresses":[
            {"address":"Test Street One"},
            {"address":"Test Street Two"},
        ]
    },
    {
        "title":"Mr.",
        "name":"Bill Smith",
        "firstName":"Bill",
        "lastName":"SMith",
        "contactType":{
            "name":"test"
        },
        "addresses":[
            {"address":"Test Street One"},
            {"address":"Test Street Two"},
        ]
    }

因此,在这种情况下,搜索将考虑对象中的任何类型和任意数量的嵌套对象。很抱歉忘了这部分。

3 个答案:

答案 0 :(得分:1)

您可以循环遍历数组的对象并使用indexof查找具有输入字符串的元素,

<强>样本

&#13;
&#13;
var myarray =[
    {
        "title":"Mr.",
        "name":"John Smith",
        "firstName":"John",
        "lastName":"Smith"
    },
    {
        "title":"Mr.",
        "name":"Bill Smith",
        "firstName":"Bill",
        "lastName":"SMith"
    }

];
var toSearch = "Mr";
var results =[];
for(var i=0; i<myarray.length; i++) {
  for(key in myarray[i]) {
    if(myarray[i][key].indexOf(toSearch)!=-1) {
      results.push(myarray[i]);
    }
  }
  }
  
  console.log(results)
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用Array#filterObject.values的组合来实现此目标:

let data = [{
    "title": "Mr.",
    "name": "John Smith",
    "firstName": "John",
    "lastName": "Smith"
  },
  {
    "title": "Mr.",
    "name": "Bill Smith",
    "firstName": "Bill",
    "lastName": "SMith"
  }

];

let string = 'Jo';
let results = data.filter(item => Object.values(item).some(value => value.includes(string)));

console.log(results);

答案 2 :(得分:0)

遍历每个对象的所有属性:

var items = [{
    "title": "Mr.",
    "name": "John Smith",
    "firstName": "John",
    "lastName": "Smith"
}, {
    "title": "Mr.",
    "name": "Bill Smith",
    "firstName": "Bill",
    "lastName": "SMith"
}];

console.log("Jo :", items.filter(x => contains(x, "Jo")).map(x => x.name));
console.log("Mr :", items.filter(x => contains(x, "Mr")).map(x => x.name));

function contains (x, w) {
  for (let k in x) {
    if (x[k].indexOf(w) !== -1) {
      return true;
    }
  }
  return false;
}