Find a value in an array of objects in Javascript
JavascriptArraysJavascript Problem Overview
I know similar questions have been asked before, but this one is a little different. I have an array of unnamed objects, which contain an array of named objects, and I need to get the object where "name" is "string 1". Here is an example array.
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
Update: I should have said this earlier, but once I find it, I want to replace it with an edited object.
Javascript Solutions
Solution 1 - Javascript
Finding the array element:
let arr = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
let obj = arr.find(o => o.name === 'string 1');
console.log(obj);
Replacing the array element:
let arr = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
let obj = arr.find((o, i) => {
if (o.name === 'string 1') {
arr[i] = { name: 'new string', value: 'this', other: 'that' };
return true; // stop searching
}
});
console.log(arr);
Solution 2 - Javascript
You can loop over the array and test for that property:
function search(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
var resultObject = search("string 1", array);
Solution 3 - Javascript
In ES6 you can use Array.prototype.find(predicate, thisArg?)
like so:
array.find(x => x.name === 'string 1')
http://exploringjs.com/es6/ch_arrays.html#_searching-for-array-elements https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find
To then replace said object (and use another cool ES6 method fill
) you could do something like:
let obj = array.find(x => x.name === 'string 1');
let index = array.indexOf(obj);
array.fill(obj.name='some new string', index, index++);
Solution 4 - Javascript
As per ECMAScript 6, you can use the findIndex
function.
array[array.findIndex(x => x.name == 'string 1')]
Solution 5 - Javascript
Considering you have following snippet:
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
You can use the following function to search for items
const search = what => array.find(element => element.name === what);
And you can check whether the item was found or not.
const found = search("string1");
if (found) {
console.log(found.value, found.other);
} else {
console.log('No result found');
}
Solution 6 - Javascript
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
var foundValue = array.filter(obj=>obj.name==='string 1');
console.log(foundValue);
Solution 7 - Javascript
With a foreach:
let itemYouWant = null;
array.forEach((item) => {
if (item.name === 'string 1') {
itemYouWant = item;
}
});
console.log(itemYouWant);
Or even better with a map:
const itemYouWant = array.map((item) => {
if (item.name === 'string 1') {
return item;
}
return null;
});
console.log(itemYouWant);
Solution 8 - Javascript
Either use a simple for
-loop:
var result = null;
for (var i = 0; i < array.length; i++) {
if (array[i].name === "string 1") {
result = array[i];
break;
}
}
Or if you can, that is, if your browser supports it, use Array.filter
, which is much more terse:
var result = array.filter(function (obj) {
return obj.name === "string 1";
})[0];
Solution 9 - Javascript
with underscore.js
use the findWhere method:
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
var result = _.findWhere(array, {name: 'string 1'});
console.log(result.name);
See this in JSFIDDLE
Solution 10 - Javascript
One line answer. You can use filter function to get result.
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
console.log(array.filter(function(arr){return arr.name == 'string 1'})[0]);
Solution 11 - Javascript
New answer
I added the prop as a parameter, to make it more general and reusable
/**
* Represents a search trough an array.
* @function search
* @param {Array} array - The array you wanna search trough
* @param {string} key - The key to search for
* @param {string} [prop] - The property name to find it in
*/
function search(array, key, prop){
// Optional, but fallback to key['name'] if not selected
prop = (typeof prop === 'undefined') ? 'name' : prop;
for (var i=0; i < array.length; i++) {
if (array[i][prop] === key) {
return array[i];
}
}
}
Usage:
var array = [
{
name:'string 1',
value:'this',
other: 'that'
},
{
name:'string 2',
value:'this',
other: 'that'
}
];
search(array, 'string 1');
// or for other cases where the prop isn't 'name'
// ex: prop name id
search(array, 'string 1', 'id');
Mocha test:
var assert = require('chai').assert;
describe('Search', function() {
var testArray = [
{
name: 'string 1',
value: 'this',
other: 'that'
},
{
name: 'string 2',
value: 'new',
other: 'that'
}
];
it('should return the object that match the search', function () {
var name1 = search(testArray, 'string 1');
var name2 = search(testArray, 'string 2');
assert.equal(name1, testArray[0]);
assert.equal(name2, testArray[1]);
var value1 = search(testArray, 'this', 'value');
var value2 = search(testArray, 'new', 'value');
assert.equal(value1, testArray[0]);
assert.equal(value2, testArray[1]);
});
it('should return undefined becuase non of the objects in the array have that value', function () {
var findNonExistingObj = search(testArray, 'string 3');
assert.equal(findNonExistingObj, undefined);
});
it('should return undefined becuase our array of objects dont have ids', function () {
var findById = search(testArray, 'string 1', 'id');
assert.equal(findById, undefined);
});
});
test results:
Search
✓ should return the object that match the search
✓ should return undefined becuase non of the objects in the array have that value
✓ should return undefined becuase our array of objects dont have ids
3 passing (12ms)
Old answer - removed due to bad practices
if you wanna know more why it's bad practice then see this article:
Why is extending native objects a bad practice?
Prototype version of doing an array search:
Array.prototype.search = function(key, prop){
for (var i=0; i < this.length; i++) {
if (this[i][prop] === key) {
return this[i];
}
}
}
Usage:
var array = [
{ name:'string 1', value:'this', other: 'that' },
{ name:'string 2', value:'this', other: 'that' }
];
array.search('string 1', 'name');
Solution 12 - Javascript
You can do it with a simple loop:
var obj = null;
for (var i = 0; i < array.length; i++) {
if (array[i].name == "string 1") {
obj = array[i];
break;
}
}
Solution 13 - Javascript
Another way (to aid @NullUserException and @Wexoni's comments) is to retrieve the object's index in the array and then go from there:
var index = array.map(function(obj){ return obj.name; }).indexOf('name-I-am-looking-for');
// Then we can access it to do whatever we want
array[index] = {name: 'newName', value: 'that', other: 'rocks'};
Solution 14 - Javascript
Similar to previous answers I used the following:
Array.prototype.getIemtByParam = function(paramPair) {
var key = Object.keys(paramPair)[0];
return this.find(function(item){return ((item[key] == paramPair[key]) ? true: false)});
}
usage:
myArray.getIemtByParam(
{name: 'Sasha'}
);
Solution 15 - Javascript
Here is the solution for search and replace
function searchAndUpdate(name,replace){
var obj = array.filter(function ( obj ) {
return obj.name === name;
})[0];
obj.name = replace;
}
searchAndUpdate("string 2","New String 2");
Solution 16 - Javascript
> Are you looking for generic Search(Filter) across the item in the object list without specifying the item key
Input
var productList = [{category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'}, {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'}, {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'}, {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'}, {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'}, {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}]
function customFilter(objList, text){
if(undefined === text || text === '' ) return objList;
return objList.filter(product => {
let flag;
for(let prop in product){
flag = false;
flag = product[prop].toString().indexOf(text) > -1;
if(flag)
break;
}
return flag;
});}
Execute
customFilter(productList, '$9');
Solution 17 - Javascript
if you are using jQuery try $.grep().
Solution 18 - Javascript
You can use query-objects from npm. You can search an array of objects using filters.
const queryable = require('query-objects');
const users = [ { firstName: 'George', lastName: 'Eracleous', age: 28 }, { firstName: 'Erica', lastName: 'Archer', age: 50 }, { firstName: 'Leo', lastName: 'Andrews', age: 20 }];
const filters = [ { field: 'age', value: 30, operator: 'lt' }, { field: 'firstName', value: 'Erica', operator: 'equals' }];
// Filter all users that are less than 30 years old AND their first name is Erica
const res = queryable(users).and(filters);
// Filter all users that are less than 30 years old OR their first name is Erica
const res = queryable(users).or(filters);
Solution 19 - Javascript
function getValue(){
for(var i = 0 ; i< array.length; i++){
var obj = array[i];
var arr = array["types"];
for(var j = 0; j<arr.length;j++ ){
if(arr[j] == "value"){
return obj;
}
}
}
}
Solution 20 - Javascript
This answer is good for typescript / Angular 2, 4, 5+
I got this answer with the help of @rujmah answer above. His answer brings in the array count... and then find's the value and replaces it with another value...
What this answer does is simply grabs the array name that might be set in another variable via another module / component... in this case the array I build had a css name of stay-dates. So what this does is extract that name and then allows me to set it to another variable and use it like so. In my case it was an html css class.
let index = this.highlightDays.indexOf(obj);
console.log('here we see what hightlightdays is ', obj.css);
let dayCss = obj.css;````