Как найти элемент в массиве объектов js

Use the find() method:

myArray.find(x => x.id === '45').foo;

From MDN:

The find() method returns the first value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned.


If you want to find its index instead, use findIndex():

myArray.findIndex(x => x.id === '45');

From MDN:

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.


If you want to get an array of matching elements, use the filter() method instead:

myArray.filter(x => x.id === '45');

This will return an array of objects. If you want to get an array of foo properties, you can do this with the map() method:

myArray.filter(x => x.id === '45').map(x => x.foo);

Side note: methods like find() or filter(), and arrow functions are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel (with the polyfill).

user229044's user avatar

user229044

231k40 gold badges328 silver badges336 bronze badges

answered Feb 14, 2016 at 21:11

Michał Perłakowski's user avatar

12

As you are already using jQuery, you can use the grep function which is intended for searching an array:

var result = $.grep(myArray, function(e){ return e.id == id; });

The result is an array with the items found. If you know that the object is always there and that it only occurs once, you can just use result[0].foo to get the value. Otherwise you should check the length of the resulting array. Example:

if (result.length === 0) {
  // no result found
} else if (result.length === 1) {
  // property found, access the foo property using result[0].foo
} else {
  // multiple items found
}

CodeJunkie's user avatar

answered Sep 9, 2011 at 15:54

Guffa's user avatar

GuffaGuffa

684k108 gold badges732 silver badges1000 bronze badges

13

Another solution is to create a lookup object:

var lookup = {};
for (var i = 0, len = array.length; i < len; i++) {
    lookup[array[i].id] = array[i];
}

... now you can use lookup[id]...

This is especially interesting if you need to do many lookups.

This won’t need much more memory since the IDs and objects will be shared.

answered Sep 9, 2011 at 15:50

Aaron Digulla's user avatar

Aaron DigullaAaron Digulla

320k108 gold badges595 silver badges816 bronze badges

14

ECMAScript 2015 (JavaScript ES6) provides the find()
method on arrays:

var myArray = [
 {id:1, name:"bob"},
 {id:2, name:"dan"},
 {id:3, name:"barb"},
]

// grab the Array item which matchs the id "2"
var item = myArray.find(item => item.id === 2);

// print
console.log(item.name);

It works without external libraries. But if you want older browser support you might want to include this polyfill.

Henke's user avatar

Henke

4,1373 gold badges31 silver badges40 bronze badges

answered Feb 10, 2014 at 22:32

Rúnar Berg's user avatar

Rúnar BergRúnar Berg

4,1591 gold badge21 silver badges38 bronze badges

7

Underscore.js has a nice method for that:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},etc.]
obj = _.find(myArray, function(obj) { return obj.id == '45' })

answered Nov 22, 2012 at 12:52

GijsjanB's user avatar

GijsjanBGijsjanB

9,9244 gold badges23 silver badges27 bronze badges

3

I think the easiest way would be the following, but it won’t work on Internet Explorer 8 (or earlier):

var result = myArray.filter(function(v) {
    return v.id === '45'; // Filter out the appropriate one
})[0].foo; // Get result and access the foo property

Peter Mortensen's user avatar

answered Sep 9, 2011 at 15:46

pimvdb's user avatar

pimvdbpimvdb

151k77 gold badges306 silver badges352 bronze badges

5

Try the following

function findById(source, id) {
  for (var i = 0; i < source.length; i++) {
    if (source[i].id === id) {
      return source[i];
    }
  }
  throw "Couldn't find object with id: " + id;
}

answered Sep 9, 2011 at 15:45

JaredPar's user avatar

JaredParJaredPar

728k148 gold badges1236 silver badges1452 bronze badges

5

myArray.filter(function(a){ return a.id == some_id_you_want })[0]

answered Apr 16, 2015 at 17:31

Danilo Colasso's user avatar

2

A generic and more flexible version of the findById function above:

// array = [{key:value},{key:value}]
function objectFindByKey(array, key, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i][key] === value) {
            return array[i];
        }
    }
    return null;
}

var array = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
var result_obj = objectFindByKey(array, 'id', '45');

answered Jul 13, 2012 at 20:34

will Farrell's user avatar

will Farrellwill Farrell

1,7071 gold badge16 silver badges21 bronze badges

Performance

Today 2020.06.20 I perform test on MacOs High Sierra on Chrome 81.0, Firefox 77.0 and Safari 13.1 for chosen solutions.

Conclusions for solutions which use precalculations

Solutions with precalculations (K,L) are (much much) faster than other solutions and will not be compared with them – probably they are use some special build-in browser optimisations

  • surprisingly on Chrome and Safari solution based on Map (K) are much faster than solution based on object {} (L)
  • surprisingly on Safari for small arrays solution based on object {} (L) is slower than traditional for (E)
  • surprisingly on Firefox for small arrays solution based on Map (K) is slower than traditional for (E)

Conclusions when searched objects ALWAYS exists

  • solution which use traditional for (E) is fastest for small arrays and fast for big arrays
  • solution using cache (J) is fastest for big arrays – surprisingly for small arrays is medium fast
  • solutions based on find (A) and findIndex (B) are fast for small arras and medium fast on big arrays
  • solution based on $.map (H) is slowest on small arrays
  • solution based on reduce (D) is slowest on big arrays

enter image description here

Conclusions when searched objects NEVER exists

  • solution based on traditional for (E) is fastest on small and big arrays (except Chrome-small arrays where it is second fast)
  • solution based on reduce (D) is slowest on big arrays
  • solution which use cache (J) is medium fast but can be speed up if we save in cache also keys which have null values (which was not done here because we want to avoid unlimited memory consumption in cache in case when many not existing keys will be searched)

enter image description here

Details

For solutions

  • without precalculations: A
    B
    C
    D
    E
    F
    G
    H
    I
    J (the J solution use ‘inner’ cache and it speed depend on how often searched elements will repeat)
  • with precalculations
    K
    L

I perform four tests. In tests I want to find 5 objects in 10 loop iterations (the objects ID not change during iterations) – so I call tested method 50 times but only first 5 times have unique id values:

  • small array (10 elements) and searched object ALWAYS exists – you can perform it HERE
  • big array (10k elements) and searched object ALWAYS exist – you can perform it HERE
  • small array (10 elements) and searched object NEVER exists – you can perform it HERE
  • big array (10k elements) and searched object NEVER exists – you can perform it HERE

Tested codes are presented below

Example tests results for Chrome for small array where searched objects always exists

enter image description here

answered Jun 20, 2020 at 22:52

Kamil Kiełczewski's user avatar

Kamil KiełczewskiKamil Kiełczewski

82.9k29 gold badges356 silver badges335 bronze badges

1

As others have pointed out, .find() is the way to go when looking for one object within your array. However, if your object cannot be found using this method, your program will crash:

const myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
const res = myArray.find(x => x.id === '100').foo; // Uh oh!
/*
Error:
"Uncaught TypeError: Cannot read property 'foo' of undefined"
or in newer chrome versions:
Uncaught TypeError: Cannot read properties of undefined (reading 'foo')
*/

This can be fixed by checking whether the result of .find() is defined before using .foo on it. Modern JS allows us to do this easily with optional chaining, returning undefined if the object cannot be found, rather than crashing your code:

const myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
const res = myArray.find(x => x.id === '100')?.foo; // No error!
console.log(res); // undefined when the object cannot be found

answered Jun 13, 2020 at 11:20

Nick Parsons's user avatar

Nick ParsonsNick Parsons

44.5k6 gold badges45 silver badges63 bronze badges

If you do this multiple times, you may set up a Map (ES6):

const map = new Map( myArray.map(el => [el.id, el]) );

Then you can simply do a O(1) lookup:

map.get(27).foo

answered Aug 8, 2017 at 15:26

Jonas Wilms's user avatar

Jonas WilmsJonas Wilms

130k20 gold badges144 silver badges150 bronze badges

You can get this easily using the map() function:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];

var found = $.map(myArray, function(val) {
    return val.id == 45 ? val.foo : null;
});

//found[0] == "bar";

Working example: http://jsfiddle.net/hunter/Pxaua/

Peter Mortensen's user avatar

answered Sep 9, 2011 at 15:46

hunter's user avatar

hunterhunter

62.1k19 gold badges113 silver badges113 bronze badges

1

Using native Array.reduce

var array = [ {'id':'73' ,'foo':'bar'} , {'id':'45' ,'foo':'bar'} , ];
var id = 73;
var found = array.reduce(function(a, b){
    return (a.id==id && a) || (b.id == id && b)
});

returns the object element if found, otherwise false

Community's user avatar

answered Jun 4, 2015 at 0:13

laggingreflex's user avatar

laggingreflexlaggingreflex

32.4k35 gold badges140 silver badges194 bronze badges

1

You can use filters,

  function getById(id, myArray) {
    return myArray.filter(function(obj) {
      if(obj.id == id) {
        return obj 
      }
    })[0]
  }

get_my_obj = getById(73, myArray);

answered Sep 13, 2013 at 9:43

Joe Lewis's user avatar

Joe LewisJoe Lewis

1,9302 gold badges17 silver badges18 bronze badges

1

While there are many correct answers here, many of them do not address the fact that this is an unnecessarily expensive operation if done more than once. In an extreme case this could be the cause of real performance problems.

In the real world, if you are processing a lot of items and performance is a concern it’s much faster to initially build a lookup:

var items = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];

var lookup = items.reduce((o,i)=>o[i.id]=o,{});

you can then get at items in fixed time like this :

var bar = o[id];

You might also consider using a Map instead of an object as the lookup: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map

answered Mar 23, 2016 at 10:24

Tom's user avatar

TomTom

7,9748 gold badges44 silver badges62 bronze badges

Recently, I have to face the same thing in which I need to search the string from a huge array.

After some search I found It’ll be easy to handle with simple code:

Code:

var items = mydata.filter(function(item){
    return item.word.toLowerCase().startsWith( 'gk );
})

See https://jsfiddle.net/maheshwaghmare/cfx3p40v/4/

Serach from 20k strings

answered Jul 25, 2019 at 10:05

maheshwaghmare's user avatar

0

Iterate over any item in the array. For every item you visit, check that item’s id. If it’s a match, return it.

If you just want teh codez:

function getId(array, id) {
    for (var i = 0, len = array.length; i < len; i++) {
        if (array[i].id === id) {
            return array[i];
        }
    }
    return null; // Nothing found
}

And the same thing using ECMAScript 5’s Array methods:

function getId(array, id) {
    var obj = array.filter(function (val) {
        return val.id === id;
    });

    // Filter returns an array, and we just want the matching item.
    return obj[0];
}

Peter Mortensen's user avatar

answered Sep 9, 2011 at 15:46

Zirak's user avatar

ZirakZirak

38.7k12 gold badges81 silver badges92 bronze badges

You may try out Sugarjs from http://sugarjs.com/.

It has a very sweet method on Arrays, .find. So you can find an element like this:

array.find( {id: 75} );

You may also pass an object with more properties to it to add another “where-clause”.

Note that Sugarjs extends native objects, and some people consider this very evil…

Peter Mortensen's user avatar

answered Nov 6, 2012 at 8:52

deepflame's user avatar

deepflamedeepflame

9281 gold badge8 silver badges19 bronze badges

3

As long as the browser supports ECMA-262, 5th edition (December 2009), this should work, almost one-liner:

var bFound = myArray.some(function (obj) {
    return obj.id === 45;
});

Peter Mortensen's user avatar

answered Apr 8, 2014 at 17:14

aggaton's user avatar

aggatonaggaton

2,9622 gold badges23 silver badges35 bronze badges

1

Here’s how I’d go about it in pure JavaScript, in the most minimal manner I can think of that works in ECMAScript 3 or later. It returns as soon as a match is found.

var getKeyValueById = function(array, key, id) {
    var testArray = array.slice(), test;
    while(test = testArray.pop()) {
        if (test.id === id) {
            return test[key];
        }
    }
    // return undefined if no matching id is found in array
    return;
}

var myArray = [{'id':'73', 'foo':'bar'}, {'id':'45', 'foo':'bar'}]
var result = getKeyValueById(myArray, 'foo', '45');

// result is 'bar', obtained from object with id of '45'

answered Feb 28, 2015 at 18:04

Dan W's user avatar

Dan WDan W

7625 silver badges8 bronze badges

More generic and short

function findFromArray(array,key,value) {
        return array.filter(function (element) {
            return element[key] == value;
        }).shift();
}

in your case Ex. var element = findFromArray(myArray,'id',45) that will give you the whole element.

answered Dec 12, 2018 at 6:35

Savan Kaneriya's user avatar

0

We can use Jquery methods $.each()/$.grep()

var data= [];
$.each(array,function(i){if(n !== 5 && i > 4){data.push(item)}}

or

var data = $.grep(array, function( n, i ) {
  return ( n !== 5 && i > 4 );
});

use ES6 syntax:

Array.find, Array.filter, Array.forEach, Array.map

Or use Lodash https://lodash.com/docs/4.17.10#filter, Underscore https://underscorejs.org/#filter

Samuel Liew's user avatar

Samuel Liew

76k106 gold badges156 silver badges257 bronze badges

answered Sep 25, 2018 at 6:49

TLbiz's user avatar

TLbizTLbiz

4878 silver badges7 bronze badges

Building on the accepted answer:

jQuery:

var foo = $.grep(myArray, function(e){ return e.id === foo_id})
myArray.pop(foo)

Or CoffeeScript:

foo = $.grep myArray, (e) -> e.id == foo_id
myArray.pop foo

Peter Mortensen's user avatar

answered Oct 23, 2014 at 14:23

stevenspiel's user avatar

stevenspielstevenspiel

5,70513 gold badges59 silver badges89 bronze badges

Use Array.prototype.filter() function.

DEMO: https://jsfiddle.net/sumitridhal/r0cz0w5o/4/

JSON

var jsonObj =[
 {
  "name": "Me",
  "info": {
   "age": "15",
   "favColor": "Green",
   "pets": true
  }
 },
 {
  "name": "Alex",
  "info": {
   "age": "16",
   "favColor": "orange",
   "pets": false
  }
 },
{
  "name": "Kyle",
  "info": {
   "age": "15",
   "favColor": "Blue",
   "pets": false
  }
 }
];

FILTER

var getPerson = function(name){
    return jsonObj.filter(function(obj) {
      return obj.name === name;
    });
}

answered May 2, 2017 at 15:40

Sumit Ridhal's user avatar

Sumit RidhalSumit Ridhal

1,3493 gold badges14 silver badges30 bronze badges

3

You can do this even in pure JavaScript by using the in built “filter” function for arrays:

Array.prototype.filterObjects = function(key, value) {
    return this.filter(function(x) { return x[key] === value; })
}

So now simply pass “id” in place of key and “45” in place of value, and you will get the full object matching an id of 45. So that would be,

myArr.filterObjects("id", "45");

answered Oct 26, 2014 at 4:39

kaizer1v's user avatar

kaizer1vkaizer1v

8988 silver badges20 bronze badges

1

I really liked the answer provided by Aaron Digulla but needed to keep my array of objects so I could iterate through it later. So I modified it to

	var indexer = {};
	for (var i = 0; i < array.length; i++) {
	    indexer[array[i].id] = parseInt(i);
	}
	
	//Then you can access object properties in your array using 
	array[indexer[id]].property

answered Nov 19, 2014 at 3:55

quincyaft's user avatar

1

Use:

var retObj ={};
$.each(ArrayOfObjects, function (index, obj) {

        if (obj.id === '5') { // id.toString() if it is int

            retObj = obj;
            return false;
        }
    });
return retObj;

It should return an object by id.

Peter Mortensen's user avatar

answered Feb 28, 2013 at 15:03

volumexxx's user avatar

2

This solution may helpful as well:

Array.prototype.grep = function (key, value) {
    var that = this, ret = [];
    this.forEach(function (elem, index) {
        if (elem[key] === value) {
            ret.push(that[index]);
        }
    });
    return ret.length < 2 ? ret[0] : ret;
};
var bar = myArray.grep("id","45");

I made it just like $.grep and if one object is find out, function will return the object, rather than an array.

Peter Mortensen's user avatar

answered Oct 22, 2014 at 9:15

soytian's user avatar

soytiansoytian

3182 silver badges3 bronze badges

2

Dynamic cached find

In this solution, when we search for some object, we save it in cache. This is middle point between “always search solutions” and “create hash-map for each object in precalculations”.

Community's user avatar

answered Jun 17, 2020 at 23:29

Kamil Kiełczewski's user avatar

Kamil KiełczewskiKamil Kiełczewski

82.9k29 gold badges356 silver badges335 bronze badges

This post will discuss how to find a value in an array of objects in JavaScript.

1. Using Array.prototype.find() function

The recommended solution is to use the find() method that returns the first occurrence of an element in the array that satisfies the given predicate. The following code example demonstrates this by finding a person with the name John.

var obj = [

    { name: ‘Max’, age: 23 },

    { name: ‘John’, age: 20 },

    { name: ‘Caley’, age: 18 }

];

var found = obj.find(e => e.name === ‘John’);

console.log(found);

/*

    Output: { name: ‘John’, age: 20 }

*/

Download  Run Code

2. Using Array.prototype.findIndex() function

Alternatively, you can use the findIndex() method, which is similar to the find() method but returns the index of the first occurrence of an element or -1 if no element is found.

var obj = [

    { name: ‘Max’, age: 23 },

    { name: ‘John’, age: 20 },

    { name: ‘Caley’, age: 18 }

];

var index = obj.findIndex(e => e.name === ‘John’);

if (index !== 1) {

    console.log(obj[index]);

}

/*

    Output: { name: ‘John’, age: 20 }

*/

Download  Run Code

3. Using Array.prototype.forEach() function

Here, the idea is to iterate over the given array using the forEach() method and determine whether the object is present in the array.

var obj = [

    { name: ‘Max’, age: 23 },

    { name: ‘John’, age: 20 },

    { name: ‘Caley’, age: 18 }

];

obj.forEach(o => {

    if (o.name === ‘John’) {

        console.log(o);

    }

});

/*

    Output: { name: ‘John’, age: 20 }

*/

Download  Run Code

4. Using Array.prototype.filter() function

Another plausible way is to filter the array to return all objects that pass the specified predicate. This can be easily done using the filter() method.

var obj = [

    { name: ‘Max’, age: 23 },

    { name: ‘John’, age: 20 },

    { name: ‘Caley’, age: 18 }

];

var found = obj.filter(e => e.name === ‘John’);

if (found.length > 0) {

    console.log(found[0]);

}

/*

    Output: { name: ‘John’, age: 20 }

*/

Download  Run Code

5. Using jQuery

The jQuery’s $.grep method works similarly to JavaScript’s native filter() method.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

const { JSDOM } = require(“jsdom”);

const { window } = new JSDOM();

var $ = require(“jquery”)(window);

var obj = [

    { name: ‘Max’, age: 23 },

    { name: ‘John’, age: 20 },

    { name: ‘Caley’, age: 18 }

];

var found = $.grep(obj, e => e.name === ‘John’);

if (found.length > 0) {

    console.log(found[0]);

}

/*

    Output: { name: ‘John’, age: 20 }

*/

Download Code

6. Using Lodash/Underscore Library

The Underscore and Lodash library have the _.filter method, similar to the JavaScript’s native filter() method. The following code example demonstrates the usage of the _.filter method.

var _ = require(‘lodash’);

var obj = [

    { name: ‘Max’, age: 23 },

    { name: ‘John’, age: 20 },

    { name: ‘Caley’, age: 18 }

];

var found = _.filter(obj, e => e.name === ‘John’);

if (found.length > 0) {

    console.log(found[0]);

}

/*

    Output: { name: ‘John’, age: 20 }

*/

Download Code

That’s all about finding the value in an array of objects in JavaScript.

I have an array of objects:

Object = {
   1 : { name : bob , dinner : pizza },
   2 : { name : john , dinner : sushi },
   3 : { name : larry, dinner : hummus }
}

I want to be able to search the object/array for where the key is “dinner”, and see if it matches “sushi”.

I know jQuery has $.inArray, but it doesn’t seem to work on arrays of objects. Or maybe I’m wrong. indexOf also seems to only work on one array level.

Is there no function or existing code for this?

Heretic Monkey's user avatar

asked Mar 3, 2011 at 13:45

Questioner's user avatar

3

If you have an array such as

var people = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" }
];

You can use the filter method of an Array object:

people.filter(function (person) { return person.dinner == "sushi" });
  // => [{ "name": "john", "dinner": "sushi" }]

In newer JavaScript implementations you can use a function expression:

people.filter(p => p.dinner == "sushi")
  // => [{ "name": "john", "dinner": "sushi" }]

You can search for people who have "dinner": "sushi" using a map

people.map(function (person) {
  if (person.dinner == "sushi") {
    return person
  } else {
    return null
  }
}); // => [null, { "name": "john", "dinner": "sushi" }, null]

or a reduce

people.reduce(function (sushiPeople, person) {
  if (person.dinner == "sushi") {
    return sushiPeople.concat(person);
  } else {
    return sushiPeople
  }
}, []); // => [{ "name": "john", "dinner": "sushi" }]

I’m sure you are able to generalize this to arbitrary keys and values!

answered Mar 3, 2011 at 14:05

ase's user avatar

asease

13.2k4 gold badges34 silver badges46 bronze badges

6

jQuery has a built-in method jQuery.grep that works similarly to the ES5 filter function from @adamse’s Answer and should work fine on older browsers.

Using adamse’s example:

var peoples = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" }
];

you can do the following

jQuery.grep(peoples, function (person) { return person.dinner == "sushi" });
  // => [{ "name": "john", "dinner": "sushi" }]

Community's user avatar

answered Mar 25, 2013 at 18:32

Zach Lysobey's user avatar

Zach LysobeyZach Lysobey

14.7k20 gold badges94 silver badges148 bronze badges

var getKeyByDinner = function(obj, dinner) {
    var returnKey = -1;

    $.each(obj, function(key, info) {
        if (info.dinner == dinner) {
           returnKey = key;
           return false; 
        };   
    });

    return returnKey;       

}

jsFiddle.

So long as -1 isn’t ever a valid key.

answered Mar 3, 2011 at 13:56

alex's user avatar

alexalex

476k200 gold badges876 silver badges980 bronze badges

1

If you’re going to be doing this search frequently, consider changing the format of your object so dinner actually is a key. This is kind of like assigning a primary clustered key in a database table. So, for example:

Obj = { 'pizza' : { 'name' : 'bob' }, 'sushi' : { 'name' : 'john' } }

You can now easily access it like this: Object['sushi']['name']

Or if the object really is this simple (just ‘name’ in the object), you could just change it to:

Obj = { 'pizza' : 'bob', 'sushi' : 'john' }

And then access it like: Object['sushi'].

It’s obviously not always possible or to your advantage to restructure your data object like this, but the point is, sometimes the best answer is to consider whether your data object is structured the best way. Creating a key like this can be faster and create cleaner code.

answered Mar 8, 2013 at 17:12

dallin's user avatar

dallindallin

8,5622 gold badges35 silver badges41 bronze badges

2

You can find the object in array with Alasql library:

var data = [ { name : "bob" , dinner : "pizza" }, { name : "john" , dinner : "sushi" },
     { name : "larry", dinner : "hummus" } ];

var res = alasql('SELECT * FROM ? WHERE dinner="sushi"',[data]);

Try this example in jsFiddle.

answered Dec 21, 2014 at 20:48

agershun's user avatar

agershunagershun

4,06738 silver badges41 bronze badges

2

You can use a simple for in loop:

for (prop in Obj){
    if (Obj[prop]['dinner'] === 'sushi'){

        // Do stuff with found object. E.g. put it into an array:
        arrFoo.push(Obj[prop]);
    }
}

The following fiddle example puts all objects that contain dinner:sushi into an array:

https://jsfiddle.net/3asvkLn6/1/

answered Jul 7, 2015 at 1:10

Rotareti's user avatar

RotaretiRotareti

48.2k21 gold badges111 silver badges106 bronze badges

There’s already a lot of good answers here so why not one more, use a library like lodash or underscore 🙂

obj = {
   1 : { name : 'bob' , dinner : 'pizza' },
   2 : { name : 'john' , dinner : 'sushi' },
   3 : { name : 'larry', dinner : 'hummus' }
}

_.where(obj, {dinner: 'pizza'})
>> [{"name":"bob","dinner":"pizza"}]

answered Jul 30, 2015 at 1:19

TomDotTom's user avatar

TomDotTomTomDotTom

6,1423 gold badges39 silver badges39 bronze badges

I had to search a nested sitemap structure for the first leaf item that machtes a given path. I came up with the following code just using .map() .filter() and .reduce. Returns the last item found that matches the path /c.

var sitemap = {
  nodes: [
    {
      items: [{ path: "/a" }, { path: "/b" }]
    },
    {
      items: [{ path: "/c" }, { path: "/d" }]
    },
    {
      items: [{ path: "/c" }, { path: "/d" }]
    }
  ]
};

const item = sitemap.nodes
  .map(n => n.items.filter(i => i.path === "/c"))
  .reduce((last, now) => last.concat(now))
  .reduce((last, now) => now);

Edit 4n4904z07

answered Oct 18, 2018 at 11:58

Marc's user avatar

MarcMarc

4,6553 gold badges27 silver badges34 bronze badges

If You want to find a specific object via search function just try something like this:

    function findArray(value){

        let countLayer = dataLayer.length;
        for(var x = 0 ; x < countLayer ; x++){

            if(dataLayer[x].user){
                let newArr = dataLayer[x].user;
                let data = newArr[value];
                return data;
            }

        }

        return null;

    }

    findArray("id");

This is an example object:

layerObj = {
    0: { gtm.start :1232542, event: "gtm.js"},
    1: { event: "gtm.dom", gtm.uniqueEventId: 52},
    2: { visitor id: "abcdef2345"},
    3: { user: { id: "29857239", verified: "Null", user_profile: "Personal", billing_subscription: "True", partners_user: "adobe"}
}

Code will iterate and find the “user” array and will search for the object You seek inside.

My problem was when the array index changed every window refresh and it was either in 3rd or second array, but it does not matter.

Worked like a charm for Me!

In Your example it is a bit shorter:

function findArray(value){

    let countLayer = Object.length;
    for(var x = 0 ; x < countLayer ; x++){

        if(Object[x].dinner === value){
            return Object[x];
        }

    }

    return null;

}

findArray('sushi');

answered Feb 24, 2020 at 14:00

z3r0's user avatar

z3r0z3r0

397 bronze badges

We use object-scan for most of our data processing. It’s conceptually very simple, but allows for a lot of cool stuff. Here is how you would solve your question

// const objectScan = require('object-scan');

const findDinner = (dinner, data) => objectScan(['*'], {
  abort: true,
  rtn: 'value',
  filterFn: ({ value }) => value.dinner === dinner
})(data);

const data = { 1: { name: 'bob', dinner: 'pizza' }, 2: { name: 'john', dinner: 'sushi' }, 3: { name: 'larry', dinner: 'hummus' } };

console.log(findDinner('sushi', data));
// => { name: 'john', dinner: 'sushi' }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>

Disclaimer: I’m the author of object-scan

answered Oct 7, 2019 at 4:13

vincent's user avatar

vincentvincent

1,8833 gold badges17 silver badges24 bronze badges

In this article, we will learn how to search and find an object in an array of objects based on particular criteria. First, we will discuss different ways in which we can find an object in an array and then move on to the different criteria through which we can search for the object.

Let’s consider an example of an array of car objects with properties of id, brand, model, price, and release_date with id having the unique value for every object.

car_list

List of cars, source: pinterest.com
const carList = [{ id:13, brand: "BMW", model: "X5", price:"$23000", release_date:"2015-10-12"},

                 { id:9, brand: "Audi", model: "S3", price:"$35000", release_date:"2013-08-23"},

                 { id:11, brand: "Bugatti", model: "Veyron", price:"$500000", release_date:"2006-02-10"},
                 
                 { id:7, brand: "VW", model: "Polo", price:"$8000", release_date:"2018-05-03"},
                
                 { id:4, brand: "Fiat", model: "Punto", price:"$6000", release_date:"2017-01-25"}]

There are two approaches to find the required object, they are as follows:

  1. Finding index of search object using Array.findIndex()
  2. Searching the object directly using Array.find()

Method 1: Array.findIndex() to find the search index

The first approach would be to find the array index of the search object using Array.findIndex(). Once the search index is found, we can access the search object by “array[index]” and then perform any required operations on the object that is found. This method is useful when we need to update the search object reference of the array.

In the below example, we find the index of the object with model value as “X5” and print the price and brand through the “carList[searchIndex]” object reference. Read more about Array.findIndex() from developer.mozilla.org/Array/findIndex.

// Finding index of the car with modal "X5" 
const searchIndex = carList.findIndex((car) => car.model=="X5");

console.log(`Model X5 is present in brand ${carList[searchIndex].brand}`);
//"Model X5 is present in brand BMW"

console.log(`The price of model X5 is ${carList[searchIndex].price}`);
//"The price of model X5 is $23000"

Method 2: Array.find() to find the search object

Another approach would be to find the search object itself by using Array.find() and assign it to a variable. Now all the search object details can be accessed from this variable. This approach is more suitable if we want to perform operations on search objects independently from the array.

In the below example, we find the object entry with model value as “X5” from the array using Array.find() and print its brand and price values. Read more about Array.find() from developer.mozilla.org/Array/find.

// Finding car object with modal "X5" 
const searchObject= carList.find((car) => car.model=="X5");

console.log(`Model X5 is present in brand ${searchObject.brand}`);
//"Model X5 is present in brand BMW"

console.log(`The price of model X5 is ${searchObject.price}`);
//"The price of model X5 is $23000"

We need criteria to search the object in the array of objects, here we will discuss 3 types of search that are as follows:

  1. Search object by unique id / Property value
  2. Search object with Min & Max property value
  3. Search object with Latest or oldest date

Find object by Unique id / Property value

The most common approach is to match the search object by unique id or property value, however, it would fail if two or more items have the same value. Simple “==” operator coupled with Array.find() will achieve a successful search operation.

In the below example, carList has a property of “id” which is unique to every object in the array. We find the car object with id = 11 from the array and print the details of the object found.

const searchId = 11;

// Finding car object with id 11
const searchObject = carList.find((car) => car.id == searchId);

const {brand, model, price} = searchObject;

console.log(`Car with id ${searchId} is ${brand} ${model}`);
//"Car with id 11 is Bugatti Veyron"

console.log(`${brand} ${model} is priced at ${price}`);
//"Bugatti Veyron is priced at $500000"

Find object with Min & Max value in array

We can find objects with minimum and maximum values in an array of objects in 3 steps:

  1. Create array of property values using Array.map((item) => item.property)
  2. Find min / max value from the array using Math.max.apply(null, array) or Math.min.apply(null, array)
  3. Find the object with max/ min value using Array.find((item) => item.property == max_value/min_Value)

In the below example, we are finding the most expensive and cheapest car object from carList array.

// Creating array with all prices in number
const prices = carList.map((car) => Number(car.price.replace("$", "")))

// Calculate higest and lowest price value
const highestPrice = "$" + Math.max.apply(null, prices);
const lowestPrice = "$" + Math.min.apply(null, prices);

// Matching values to find the expensive and cheap car
const expensiveCar = carList.find((car) => car.price == highestPrice)
const cheapCar = carList.find((car) => car.price == lowestPrice)

console.log(`Most expensive Car is ${expensiveCar.brand} ${expensiveCar.model} at ${highestPrice}`)
// "Most expensive Car is Bugatti Veyron at $500000"

console.log(`Cheapest Car is ${cheapCar.brand} ${cheapCar.model} at ${lowestPrice}`)
// "Cheapest Car is Fiat Punto at $6000"

Based on Latest or Oldest Date

We need to follow 4 steps to find an object with a min/max date from the array of objects:

  1. Make sure the date field of objects are in YYYY-MM-DD format.
  2. Define callback function for max value which returns Date.parse(car1.release_date) < (Date.parse(car2.release_date) ? a : b
  3. Callback function for min value with Date.parse(car1.release_date) > (Date.parse(car2.release_date) ? a : b
  4. Apply Array.reduce() with the callback function and assign the return value to a variable

In the below example, we find cars with the oldest and latest release date from carList array based on the “release_date” property value.

// "Get car with oldest release date"
const oldestCar = carList.reduce((car1, car2) => {
  return (Date.parse(car1.release_date)) < (Date.parse(car2.release_date)) ? a : b;
});

console.log(`The Oldest Car is ${oldestCar.brand} ${oldestCar.model} at ${oldestCar.release_date}`)
// "The Oldest Car is Bugatti Veyron at 2006-02-10"

// "Get car with latest release date"
const latestCar = carList.reduce((car1, car2) => {
  return (Date.parse(car1.release_date)) > (Date.parse(car2.release_date)) ? a : b;
});

console.log(`The Latest Car is ${latestCar.brand} ${latestCar.model} at ${latestCar.release_date}`)
//"The Latest Car is VW Polo at 2018-05-03"

Trusted answers to developer questions

Shubham Singh Kshatriya

Grokking the Behavioral Interview

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

Overview

In JavaScript, we can use the Array.prototype.find() method to find an object by ID in an array of objects.

Return value

This method returns the first object instance that matches the specified condition in the callback function. If none of the objects match the specified condition, this method returns undefined.

Example

Let’s look at the code below:

// array of objects to be queried

const array = [

{

id: 1,

name: 'Shubham'

},

{

id: 2,

name: 'Parth'

},

{

id: 3,

name: 'Pratik'

}

]

// finding the object whose id is '3'

const object = array.find(obj => obj.id === 3);

// printing object on the console

console.log(object)

Finding an object by ID in an array of JavaScript objects

Explanation

  • Lines 2 to 15: We create an array of objects.
  • Line 18: We use the Array.prototype.find() method to find an object with id=3.
  • Line 21: We print the resultant object on the console.

CONTRIBUTOR

Shubham Singh Kshatriya

Trusted Answers to Developer Questions

Learn in-demand tech skills in half the time

Copyright ©2023 Educative, Inc. All rights reserved.

soc2

Did you find this helpful?

Добавить комментарий