0

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;
    }
  });
}
3
  • You probably want filter. Commented Nov 4, 2014 at 5:01
  • 2
    Too bad ES6 isn't really supported yet: return arr.find(el => el[searchKey] === searchValue); Commented Nov 4, 2014 at 5:05
  • @Qantas94Heavy It still is in draft :( Commented Nov 4, 2014 at 5:06

5 Answers 5

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @thefourtheye - I'll accept the answer when the timer is up. Do you also happen to know how I can delete this from the array? Looks like deletion requires me to know the index of the element in the array.
@DonnyP You can use _.filter as shown in other answers, which will give a new array without the unwanted elements. So, we can ditch the old array and start using the new array.
1

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')})

Comments

1

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"}]

1 Comment

filter is only appropriate if you want an array of all matches. To find just one match, it would be _.find.
0

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.

Comments

0

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"));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.