Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

javascript - Filter array of objects on all properties value

I am really surprised I haven't been able to find anything related to my question. I am looking for a fast way to filter my array of objects based on a user text input.

Assume I have this array:

let data = [{
  "id": 1,
  "first_name": "Jean",
  "last_name": "Owens",
  "email": "[email protected]",
  "gender": "Female"
}, {
  "id": 2,
  "first_name": "Marie",
  "last_name": "Morris",
  "email": "[email protected]",
  "gender": "Female"
}, {
  "id": 3,
  "first_name": "Larry",
  "last_name": "Wallace",
  "email": "[email protected]",
  "gender": "Male"
}];

User writes "s", the expected result would be:

let result = [{
  "id": 1,
  "first_name": "Jean",
  "last_name": "Owens",
  "email": "[email protected]",
  "gender": "Female"
}, {
  "id": 2,
  "first_name": "Marie",
  "last_name": "Morris",
  "email": "[email protected]",
  "gender": "Female"
}]

I could use the filter function in such a way:

let = searchText = "s";
    let result = data.filter(object=>{
      for (var property in object) {
        if (object.hasOwnProperty(property)) {
          return object[property].toString().toLowerCase().indexOf(searchText) !== -1;
        }
      }
    });

So I am wondering if there are better alternatives to this solution?

--Here is a working JsFiddle thanks to KoolShams

--Plunker for benchmark purposes (tested with 2k data)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use Object.keys() and some() instead.

let data = [{
  "id": 1,
  "first_name": "Jean",
  "last_name": "Owens",
  "email": "[email protected]",
  "gender": "Female"
}, {
  "id": 2,
  "first_name": "Marie",
  "last_name": "Morris",
  "email": "[email protected]",
  "gender": "Female"
}, {
  "id": 3,
  "first_name": "Larry",
  "last_name": "Wallace",
  "email": "[email protected]",
  "gender": "Male"
}];

var result = data.filter(function(o) {
  return Object.keys(o).some(function(k) {
    return o[k].toString().toLowerCase().indexOf('s') != -1;
  })
})

console.log(result)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...