Как найти object в javascript

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 badges999 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,1673 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,7051 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

83.1k29 gold badges359 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.7k6 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,9402 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,9922 gold badges23 silver badges36 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

76.1k107 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 badges60 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

83.1k29 gold badges359 silver badges335 bronze badges

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

477k200 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,6012 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.3k21 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,1603 gold badges40 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,6653 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

Wzhik

К сайту подключается код метрики, не секрет, что имя объекта метрики после создания имеет вид yaCounterXXXXXXX. Вопрос в том как получить доступ к объекту метрики, не зная полного имени объекта. Может быть есть какие-то способы перебора всех объявленных глобальных объектов?


  • Вопрос задан

    более трёх лет назад

  • 248 просмотров

var counterId = document.body.innerHTML.match(/yaCounter[0-9]{1,}/)[0]
var objMetrika = window[counter];

Пригласить эксперта

Ищите в window. Так же при подключении метрики в window появляется поле “Ya”.

for (var key in window) {
    if (key.match(/^yaCounterd+$/)) {
        console.log(key);
    }
}

Object.keys(window).forEach(function(key){

if ( key.match(/^yaCounterd+$/) ) {
console.log( key, window[key]);
}

})


  • Показать ещё
    Загружается…

25 мая 2023, в 02:38

1000 руб./за проект

25 мая 2023, в 02:31

800 руб./за проект

25 мая 2023, в 01:56

1200 руб./за проект

Минуточку внимания

В этом посте мы обсудим, как определить, содержит ли массив объект с заданным атрибутом в JavaScript.

1. Использование some() метод

Рекомендуемое решение — использовать some() метод, возвращающий true, если в массиве найден хотя бы один объект, удовлетворяющий заданному условию, и false в противном случае.

Следующий пример демонстрирует это, находя человека, живущего в штате NYC.

const people = [

    { name : ‘Jane Smith’, city : ‘New York City’, state : ‘NYC’, zip : ‘10001’ },

    { name : ‘Bob Brown’, city : ‘Colorado’, state : ‘CO’, zip : ‘80011’ },

    { name : ‘Alice Brown’, city : ‘Michigan’, state : ‘MI’, zip : ‘48002’ }

];

const isPresent = people.some(e => e.state === ‘NYC’);

console.log(isPresent);

/*

    результат: true

*/

Скачать  Выполнить код

2. Использование find() метод

Другим решением является использование find() метод, который возвращает первый экземпляр объекта в массиве, который удовлетворяет данному тесту или undefined если он не найден.

const people = [

    { name : ‘Jane Smith’, city : ‘New York City’, state : ‘NYC’, zip : ‘10001’ },

    { name : ‘Bob Brown’, city : ‘Colorado’, state : ‘CO’, zip : ‘80011’ },

    { name : ‘Alice Brown’, city : ‘Michigan’, state : ‘MI’, zip : ‘48002’ }

];

const isPresent = people.find(e => e.state === ‘NYC’) !== undefined;

console.log(isPresent);

/*

    результат: true

*/

Скачать  Выполнить код

3. Использование findIndex() метод

В качестве альтернативы вы можете использовать findIndex() метод, аналогичный методу find() метод, за исключением того, что он возвращает индекс первого экземпляра объекта или -1 если объект не найден.

const people = [

    { name : ‘Jane Smith’, city : ‘New York City’, state : ‘NYC’, zip : ‘10001’ },

    { name : ‘Bob Brown’, city : ‘Colorado’, state : ‘CO’, zip : ‘80011’ },

    { name : ‘Alice Brown’, city : ‘Michigan’, state : ‘MI’, zip : ‘48002’ }

];

const isPresent = people.findIndex(e => e.state === ‘NYC’) !== 1;

console.log(isPresent);

/*

    результат: true

*/

Скачать  Выполнить код

4. Использование filter() метод

Другой вероятный способ — отфильтровать массив, чтобы вернуть все объекты, соответствующие заданному условию. Это можно легко сделать с помощью filter() метод.

const people = [

    { name : ‘Jane Smith’, city : ‘New York City’, state : ‘NYC’, zip : ‘10001’ },

    { name : ‘Bob Brown’, city : ‘Colorado’, state : ‘CO’, zip : ‘80011’ },

    { name : ‘Alice Brown’, city : ‘Michigan’, state : ‘MI’, zip : ‘48002’ }

];

const isPresent = people.filter(e => e.state === ‘NYC’).length > 0;

console.log(isPresent);

/*

    результат: true

*/

Скачать  Выполнить код

5. Использование forEach() метод

Наконец, вы можете выполнить итерацию по массиву, используя forEach() метод и проверьте наличие объекта в массиве.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

const people = [

    { name : ‘Jane Smith’, city : ‘New York City’, state : ‘NYC’, zip : ‘10001’ },

    { name : ‘Bob Brown’, city : ‘Colorado’, state : ‘CO’, zip : ‘80011’ },

    { name : ‘Alice Brown’, city : ‘Michigan’, state : ‘MI’, zip : ‘48002’ }

];

var isPresent = false;

people.forEach(o => {

    if (e => e.state === ‘NYC’) {

        isPresent = true;

    }

});

console.log(isPresent);

/*

    результат: true

*/

Скачать  Выполнить код

Это все о проверке, содержит ли массив объект с заданным атрибутом в JavaScript.

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