问题
Given an array of objects, what is the best way to find the object with a particular key in JS?
Using jQuery and underscoreJS is fine. I'm just looking for the easiest / least code answer.
Example: An array of objects, where each object has a "name". Find the object with a particular "name".
var people = [{name: "A"}, {name: "B"}, {name: "C"}];
My current solution: Pass in the array, the key (e.g. "name"), and the value (e.g. "C").
function getObject(myArray, searchKey, searchValue) {
myArray.forEach(function(element){
if (element[searchKey] == searchValue) {
return element;
}
});
}
回答1:
You can use Underscore.js's _.where function, like this
console.log(_.where(people, {
"name": "C"
}));
# [ { name: 'C' } ]
This returns all the objects in the array, which exactly matches the object we pass as the second argument.
回答2:
You should go with grep of jQuery
var people = [{name: "A"}, {name: "B"}, {name: "C"}];
var obj1= jQuery.grep(people,function(n,i){return (n.name=='A')})
回答3:
Using _.filter:
var people = [{name: "A"}, {name: "B"}, {name: "C"}];
var filteredPeople = _.filter(people, function(obj){
return obj['name'] == 'C';
});
console.log(JSON.stringify(filteredPeople)) // [{"name":"C"}]
If you want an array without the matched object(s), use _.reject:
var filteredPeople = _.reject(people, function(obj){
return obj['name'] == 'C';
});
console.log(JSON.stringify(filteredPeople)) // [{name: "A"}, {name: "B"}]
回答4:
Without any custom library you can also do this. Please take a look at the following code
var people = [{name: "A"}, {name: "B"}, {name: "C"}],
match=function(element){
return element.name==="A";
};
console.log(people.filter(match));
But it is kind of static code . I don't know how to pass the key and value to the match() function.
回答5:
I'm surprised not to find the obvious answer here, so: To do that with Underscore, you'd use _.find:
function getObject(myArray, searchKey, searchValue) {
return _.find(myArray, function(entry) { return entry[seachKey] === searchValue; });
}
You don't need Underscore for this, though; JavaScript's array type has find
(as of ES5):
function getObject(myArray, searchKey, searchValue) {
return myArray.find(function(entry) { return entry[searchKey] === searchValue; });
}
As of ES2015+, you can make it more concise with an arrow function and destructuring:
function getObject(myArray, searchKey, searchValue) {
return myArray.find(({[searchKey]: value}) => value === searchValue);
}
Live example of that last one:
function getObject(myArray, searchKey, searchValue) {
return myArray.find(({[searchKey]: value}) => value === searchValue);
}
const people = [{name: "A"}, {name: "B"}, {name: "C"}];
console.log(getObject(people, "name", "C"));
来源:https://stackoverflow.com/questions/26728022/given-an-array-of-objects-find-the-object-with-a-particular-key