Javascript как найти элемент в объекте

I have an array of homogeneous objects like so;

[
  {
    "foo" : "bar",
    "bar" : "sit"
  },
  {
    "foo" : "lorem",
    "bar" : "ipsum"
  },
  {
    "foo" : "dolor",
    "bar" : "amet"
  }
]

I’d like to search these objects’ values (not keys) with a keyword, and return an array of objects that contain the keyword in any of the values.

So for example, with a keyword r, I would get all the objects («baR» in object #1, «loRem» in object #2 and «doloR» in object #3). With a keyword lo, I would get objects 2 and 3 («LOrem» and «doLOr»), with a, I’d get objects 1 and 3, («bAr» and «Amet»). With the keyword foo however, I would get an empty array, since «foo» is a key, and isn’t found in any of the values (unlike «bar»)… you get the idea.

How would I go about doing this? Thanks a lot in advance!

asked Dec 15, 2011 at 8:25

Emphram Stavanger's user avatar

1

Something like this:

var objects = [
  {
    "foo" : "bar",
    "bar" : "sit"
  },
  {
    "foo" : "lorem",
    "bar" : "ipsum"
  },
  {
    "foo" : "dolor",
    "bar" : "amet"
  }
];

var results = [];

var toSearch = "lo";

for(var i=0; i<objects.length; i++) {
  for(key in objects[i]) {
    if(objects[i][key].indexOf(toSearch)!=-1) {
      results.push(objects[i]);
    }
  }
}

The results array will contain all matched objects.

If you search for ‘lo’, the result will be like:

[{ foo="lorem", bar="ipsum"}, { foo="dolor", bar="amet"}]

NEW VERSION — Added trim code, code to ensure no duplicates in result set.

function trimString(s) {
  var l=0, r=s.length -1;
  while(l < s.length && s[l] == ' ') l++;
  while(r > l && s[r] == ' ') r-=1;
  return s.substring(l, r+1);
}

function compareObjects(o1, o2) {
  var k = '';
  for(k in o1) if(o1[k] != o2[k]) return false;
  for(k in o2) if(o1[k] != o2[k]) return false;
  return true;
}

function itemExists(haystack, needle) {
  for(var i=0; i<haystack.length; i++) if(compareObjects(haystack[i], needle)) return true;
  return false;
}

var objects = [
  {
    "foo" : "bar",
    "bar" : "sit"
  },
  {
    "foo" : "lorem",
    "bar" : "ipsum"
  },
  {
    "foo" : "dolor blor",
    "bar" : "amet blo"
  }
];

function searchFor(toSearch) {
  var results = [];
  toSearch = trimString(toSearch); // trim it
  for(var i=0; i<objects.length; i++) {
    for(var key in objects[i]) {
      if(objects[i][key].indexOf(toSearch)!=-1) {
        if(!itemExists(results, objects[i])) results.push(objects[i]);
      }
    }
  }
  return results;
}

console.log(searchFor('lo '));

answered Dec 15, 2011 at 8:32

techfoobar's user avatar

techfoobartechfoobar

65.3k14 gold badges113 silver badges134 bronze badges

13

All the other old answers use a for in loop, modern JavaScript has Object.keys. Combine that with some, includes, and filter and it is a bit nicer.

var a = [{
  name: 'xyz',
  grade: 'x'
}, {
  name: 'yaya',
  grade: 'x'
}, {
  name: 'x',
  frade: 'd'
}, {
  name: 'a',
  grade: 'b'
}];

function filterIt(arr, searchKey) {
  return arr.filter(function(obj) {
    return Object.keys(obj).some(function(key) {
      return obj[key].includes(searchKey);
    })
  });
}

console.log("find 'x'", filterIt(a,"x"));
console.log("find 'a'", filterIt(a,"a"));
console.log("find 'z'", filterIt(a,"z"));

Or with ES6

function filterIt(arr, searchKey) {
  return arr.filter(obj => Object.keys(obj).some(key => obj[key].includes(searchKey)));
}

answered Nov 30, 2016 at 14:18

epascarello's user avatar

epascarelloepascarello

203k20 gold badges193 silver badges234 bronze badges

7

This is a cool solution that works perfectly

const array = [{"title":"tile hgfgfgfh"},{"title":"Wise cool"},{"title":"titlr DEytfd ftgftgfgtgtf gtftftft"},{"title":"This is the title"},{"title":"yeah this is cool"},{"title":"tile hfyf"},{"title":"tile ehey"}];

var item = array.filter(item=>item.title.toLowerCase().includes('this'));

 alert(JSON.stringify(item))

EDITED

const array = [{"title":"tile hgfgfgfh"},{"title":"Wise cool"},{"title":"titlr DEytfd ftgftgfgtgtf gtftftft"},{"title":"This is the title"},{"title":"yeah this is cool"},{"title":"tile hfyf"},{"title":"tile ehey"}];


// array.filter loops through your array and create a new array returned as Boolean value given out "true" from eachIndex(item) function 

var item = array.filter((item)=>eachIndex(item));

//var item = array.filter();



function eachIndex(e){
console.log("Looping each index element ", e)
return e.title.toLowerCase().includes("this".toLowerCase())
}

console.log("New created array that returns "true" value by eachIndex ", item)

answered May 4, 2018 at 18:31

General Omosco's user avatar

General OmoscoGeneral Omosco

5961 gold badge10 silver badges20 bronze badges

2

This is a succinct way with modern Javascript:

var objects = [
  {
    "foo" : "bar",
    "bar" : "sit"
  },
  {
    "foo" : "lorem",
    "bar" : "ipsum"
  },
  {
    "foo" : "dolor blor",
    "bar" : "amet blo"
  }
];

const query = "lo";
const filteredItems = objects.filter(item => `${item.foo} ${item.bar}`.includes(query));

answered Mar 5, 2021 at 22:14

Edison Arango's user avatar

This is a proposal which uses the key if given, or all properties of the object for searching a value.

function filter(array, value, key) {
    return array.filter(key
        ? a => a[key] === value
        : a => Object.keys(a).some(k => a[k] === value)
    );
}

var a = [{ name: 'xyz', grade: 'x' }, { name: 'yaya', grade: 'x' }, { name: 'x', frade: 'd' }, { name: 'a', grade: 'b' }];


console.log(filter(a, 'x'));
console.log(filter(a, 'x', 'name'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

D Malan's user avatar

D Malan

10.1k3 gold badges25 silver badges49 bronze badges

answered Nov 30, 2016 at 14:23

Nina Scholz's user avatar

Nina ScholzNina Scholz

374k25 gold badges344 silver badges386 bronze badges

2

The search function will return all objects which contain a value which has contains the search query

function search(arr, s){
    var matches = [], i, key;
    
    for( i = arr.length; i--; )
        for( key in arr[i] )
            if( arr[i].hasOwnProperty(key) && arr[i][key].indexOf(s) > -1 )
                matches.push( arr[i] );  // <-- This can be changed to anything

    return matches;
};

// dummy data
var items = [
      {
        "foo" : "bar",
        "bar" : "sit"
      },
      {
        "foo" : "lorem",
        "bar" : "ipsum"
      },
      {
        "foo" : "dolor",
        "bar" : "amet"
      }
];
    
var result = search(items, 'lo'); // search "items" for a query value
console.log(result); // print the result

answered Dec 15, 2011 at 8:41

vsync's user avatar

vsyncvsync

116k56 gold badges302 silver badges393 bronze badges

2

Modern Javascript 😄

const objects = [
    {
        "foo" : "bar",
        "bar" : "sit"
    },
    {
        "foo" : "lorem",
        "bar" : "ipsum"
    },
    {
        "foo" : "dolor blor",
        "bar" : "amet blo"
    }
];

const keyword = 'o';

const results = objects.filter(object => Object.values(object).some(i => i.includes(keyword)));
console.log(results);

// results [{ foo: 'lorem', bar: 'ipsum' },{ foo: 'dolor blor', bar: 'amet blo' }]

answered Aug 15, 2020 at 9:59

Asaf's user avatar

AsafAsaf

8891 gold badge12 silver badges14 bronze badges

search(searchText) {
  let arrayOfMatchedObjects = arrayOfAllObjects.filter(object => {
    return JSON.stringify(object)
      .toString()
      .toLowerCase()
      .includes(searchText);
  });
  return arrayOfMatchedObjects;
}

This could be very simple, easy, fast and understandable Search function for some of you just like me.

answered Dec 25, 2019 at 19:56

Awais Jameel's user avatar

Awais JameelAwais Jameel

1,70217 silver badges12 bronze badges

1

var search(subject, objects) {

    var matches = [];
    var regexp = new RegExp(subject, 'g');

    for (var i = 0; i < objects.length; i++) {
        for (key in objects[i]) {
            if (objects[i][key].match(regexp)) matches.push(objects[i][key]);
        }
    }
    return matches;
};

var items = [
  {
    "foo" : "bar",
    "bar" : "sit"
  },
  {
    "foo" : "lorem",
    "bar" : "ipsum"
  },
  {
    "foo" : "dolor",
    "bar" : "amet"
  }
];

search('r', items);    // ["bar", "lorem", "dolor"]

answered Dec 15, 2011 at 8:27

Michael Robinson's user avatar

Michael RobinsonMichael Robinson

29.1k12 gold badges104 silver badges130 bronze badges

0

As a Javascripter Lv. 1 I just learned to search for strings in objects with this:

function isThere( a_string, in_this_object )
{
    if( typeof a_string != 'string' )
    {
        return false;
    }

    for( var key in in_this_object )
    {
        if( typeof in_this_object[key] == 'object' || typeof in_this_object[key] == 'array' )
        {
            if ( isThere( a_string, in_this_object[key] ) )
            {
                return true;
            }
        }
        else if( typeof in_this_object[key] == 'string' )
        {
            if( a_string == in_this_object[key] )
            {
                return true;
            }
        }
    }

    return false;
}

I know is far from perfect but it is useful.

Feel free to comment in order to improve this.

Goose's user avatar

Goose

4,7445 gold badges43 silver badges84 bronze badges

answered Nov 27, 2014 at 23:45

Gera's user avatar

2

Although a bit late, but a more compact version may be the following:

/**
* @param {string} quickCriteria Any string value to search for in the object properties.
* @param {any[]} objectArray The array of objects as the search domain
* @return {any[]} the search result
*/
onQuickSearchChangeHandler(quickCriteria, objectArray){

   let quickResult = objectArray.filter(obj => Object.values(obj).some(val => val?val.toString().toLowerCase().includes(quickCriteria):false));

   return quickResult;
}

It can handle falsy values like false, undefined, null and all the data types that define .toString() method like number, boolean etc.

answered Apr 26, 2018 at 19:49

Nadeem Jamali's user avatar

Nadeem JamaliNadeem Jamali

1,3533 gold badges16 silver badges27 bronze badges

You can use this javascript lib, DefiantJS (http://defiantjs.com), with which you can filter matches using XPath on JSON structures. To put it in JS code:

    var data = [
       { "foo": "bar",   "bar": "sit" },
       { "foo": "lorem", "bar": "ipsum" },
       { "foo": "dolor", "bar": "amet" }
    ],
    res1 = JSON.search( data, '//*[contains(name(), 'r')]/..' ),
    res2 = JSON.search( data, '//*[contains(., 'lo')]' );

/*
res1 = [
    { "foo": "bar",   "bar": "sit" },
    { "foo": "lorem", "bar": "ipsum" },
    { "foo": "dolor", "bar": "amet" }
]
*/

/*
res2 = [
    { "foo": "lorem", "bar": "ipsum" },
    { "foo": "dolor", "bar": "amet" }
]
*/

Here is a working fiddle;
http://jsfiddle.net/hbi99/2kHDZ/

DefiantJS extends the global object with the method «search» and returns an array with matches (empty array if no matches were found). You can try out the lib and XPath queries using the XPath Evaluator here:

http://www.defiantjs.com/#xpath_evaluator

answered Jan 5, 2014 at 10:52

Hakan Bilgin's user avatar

Hakan BilginHakan Bilgin

1,11312 silver badges11 bronze badges

I needed to perform a search on a large object and return the addresses of the matches, not just the matched values themselves.

This function searches an object for a string (or alternatively, uses a callback function to perform custom logic) and keeps track of where the value was found within the object. It also avoids circular references.

//Search function
var locateInObject = function(obj, key, find, result, currentLocation){
  if(obj === null) return;
  result = result||{done:[],found:{}};
  if(typeof obj == 'object'){
    result.done.push(obj);
  }
  currentLocation = currentLocation||key;
  var keys = Object.keys(obj);
  for(var k=0; k<keys.length; ++k){
    var done = false;
    for(var d=0; d<result.done.length; ++d){
      if(result.done[d] === obj[keys[k]]){
        done = true;
        break;
      }
    }
    if(!done){
      var location = currentLocation+'.'+keys[k];
      if(typeof obj[keys[k]] == 'object'){
        locateInObject(obj[keys[k]], keys[k], find, result, location)
      }else if((typeof find == 'string' && obj[keys[k]].toString().indexOf(find) > -1) || (typeof find == 'function' && find(obj[keys[k]], keys[k]))){
        result.found[location] = obj[keys[k]];
      }
    }
  }
  return result.found;
}

//Test data
var test = {
  key1: {
    keyA: 123,
    keyB: "string"
  },
  key2: {
    keyC: [
      {
        keyI: "string123",
        keyII: 2.3
      },
      "string"
    ],
    keyD: null
  },
  key3: [
    1,
    2,
    123,
    "testString"
  ],
  key4: "123string"
}
//Add a circular reference
test.key5 = test;

//Tests
console.log(locateInObject(test, 'test', 'string'))
console.log(locateInObject(test, 'test', '123'))
console.log(locateInObject(test, 'test', function(val, key){ return key.match(/keyd/) && val.indexOf('string') > -1}))

answered May 31, 2019 at 14:00

JstnPwll's user avatar

JstnPwllJstnPwll

8,5752 gold badges33 silver badges56 bronze badges

Came across this problem today and using a modified version of the provided code by epascarello in this thread did the trick, because that version had trouble when the object contained some values others than strings (like a number of booleans for example).

console.log('find: ', findIn(arrayOfObjects, searchKey));

const findIn = (arr, searchKey) => {
 return arr.filter(obj => 
  Object.keys(obj).some(key => {
   if (typeof obj[key] === 'string') {
    return obj[key].includes(searchKey);
   }
  })
 );
};

answered Nov 22, 2019 at 2:34

Ceryx's user avatar

CeryxCeryx

211 bronze badge

1

Here is the answer in 100% PURE JavaScript:

<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title></title>
  <script type="text/javascript">
    var mySet = [{
        "foo": "bar",
        "bar": "sit"
      },
      {
        "foo": "lorem",
        "bar": "ipsum"
      },
      {
        "foo": "dolor",
        "bar": "amet"
      }
    ];

    function queryObject(needle, set) {
      var results = new Array();
      for (index = 0; index < set.length; index++) {
        for (key in set[index]) {
          if (set[index][key].indexOf(needle) > -1) {
            results.push(set[index]);
          }
        }
      }

      if (results.length) {
        return JSON.stringify(results);
      } else {
        return "No match!";
      }
    }
  </script>
</head>

<body>
  <form>
    <input type="text" id="prompt" onFocus="this.value='';" value="Type your query HERE" size="20" onKeyDown="document.getElementById('submit').disabled = false;">
    <input id="submit" type="button" value="Find in Object" onClick="var prompt=document.getElementById('prompt'); if(prompt.value){document.getElementById('output').innerHTML = queryObject(prompt.value, mySet);}else{prompt.value='Type your query HERE';}"
      disabled="disabled">
    <div id="output"></div>
  </form>
</body>

</html>

There are, of course, more fancy ways to traverse your object using JQuery, but this is the basic concept.

Cheers!

*EDIT: Sorry, I didn’t read your question carefully enough, and modified the code to return an array of objects as you requested.

Not A Bot's user avatar

Not A Bot

2,4622 gold badges15 silver badges32 bronze badges

answered Dec 15, 2011 at 9:10

lincolnberryiii's user avatar

2

MAKE SIMPLE

const objects = [
     {
     "foo" : "bar",
     "bar" : "sit",
     "date":"2020-12-20"
     },
     {
     "foo" : "lorem",
     "bar" : "ipsum",
     "date":"2018-07-02"
     },
     {
     "foo" : "dolor",
     "bar" : "amet",
     "date":"2003-10-08"
     },
     {
     "foo" : "lolor",
     "bar" : "amet",
     "date":"2003-10-08"
     }
     ];
     
     
     
     const filter = objects.filter(item => {
     const obj = Object.values(item)
     return obj.join("").indexOf('2003') !== -1
     })
     
     console.log(filter)

answered Sep 21, 2020 at 20:58

Vitor de oliveira's user avatar

Just another variation using ES6, this is what I use.

// searched keywords    
const searchedWord = "My searched exp";

// array of objects
let posts = [
    {
        text_field: "lorem ipsum doleri imet",
        _id: "89789UFJHDKJEH98JDKFD98"
    }, 
    {
        text_field: "ipsum doleri imet",
        _id: "JH738H3JKJKHJK93IOHLKL"
    }
];

// search results will be pushed here
let matches = [];

// regular exp for searching
let regexp = new RegExp(searchedWord, 'g');

// looping through posts to find the word
posts.forEach((post) => {
    if (post["text_field"].match(regexp)) matches.push(post);
});

answered Dec 8, 2017 at 11:51

moolsbytheway's user avatar

Below shared for specific given property

searchContent:function(s, arr,propertyName){
            var matches = [];
            var propertyNameString=this.propertyNameToStr(propertyName);
            for (var i = arr.length; i--; ){
                if((""+Object.getOwnPropertyDescriptor(arr[i], propertyNameString).value).indexOf(s) > -1)
                    matches.push(arr[i]);
            }
            return matches;
        },
    propertyNameToStr: function (propertyFunction) {
            return /.([^.;]+);?s*}$/.exec(propertyFunction.toString())[1];
    }

//usage as below

result=$localStorage.searchContent(cabNo,appDataObj.getAll(),function() { dummy.cabDriverName; })

answered Aug 29, 2016 at 14:13

Syed Raheem Uddin's user avatar

I’ve found a way that you can search in nested object like everything search , for example list of student that have nested lesson object:

var students=[{name:"ali",family:"romandeh",age:18,curse:[
   {lesson1:"arabic"},
   {lesson2:"english"},
   {lesson3:"history"}
   ]},
   {name:"hadi",family:"porkar",age:48,curse:[
   {lesson1:"arabic"},
   {lesson2:"english"},
   {lesson3:"history"}
   ]},
   {name:"majid",family:"porkar",age:30,curse:[
   {lesson1:"arabic"},
   {lesson2:"english"},
   {lesson3:"history"}
   ]}
   ];
  
    function searchInChild(objects, toSearch){
        var _finded=false;
        for(var i=0; i<objects.length; i++) {
            for(key in objects[i]) {
                if(objects[i][key]!=null && typeof(objects[i][key] )!="boolean" && typeof(objects[i][key] )!="number"){
                    if (typeof objects[i][key] == 'object') {
                        _finded= searchInChild(objects[i][key],toSearch);

                    }
                    else if(objects[i][key].indexOf(toSearch)!=-1) {
                        _finded=true;
                    }
                }
            }
        }
        return _finded;
    }
    function findNested(objects, toSearch) {
        var _results=[];
        for(var i=0; i<objects.length; i++) {
            for(key in objects[i]) {
                if(objects[i][key]!=null && typeof(objects[i][key] )!="boolean" && typeof(objects[i][key] )!="number"){
                    if (typeof objects[i][key] == 'object') {
                        if(searchInChild(objects[i][key],toSearch)){
                            _results.push(objects[i]);
                        }
                    }
                    else if(objects[i][key].indexOf(toSearch)!=-1) {
                        _results.push(objects[i]);
                    }
                }
            }
        }

        return _results;

    }
    $('.quickSearch').on('click',function(){
          var _inputSeach=$('#evertingSearch').val();
          if(_inputSeach!=''){
          var _finded=findNested(students,_inputSeach);
          $('.count').html(_finded.length);}
    
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<span>
<pre><code>
       var students=[{name:"ali",family:"romandeh",age:18,curse:[
   {lesson1:"arabic"},
   {lesson2:"english"},
   {lesson3:"history"}
   ]},
   {name:"hadi",family:"porkar",age:48,curse:[
   {lesson1:"arabic"},
   {lesson2:"english"},
   {lesson3:"history"}
   ]},
   {name:"majid",family:"rezaeiye",age:30,curse:[
   {lesson1:"arabic"},
   {lesson2:"english"},
   {lesson3:"history"}
   ]}
   ];
</code></pre>

<span>

<input id="evertingSearch" placeholder="Search on students" />
<input type="button" class="quickSearch" value="search" />
<lable>count:</lable><span class="count"></span>


</body>



</html>

answered Dec 16, 2018 at 8:02

Mahdi Porkar's user avatar

I have created this easy to use library that does exactly what you are looking for: ss-search

import { search } from "ss-search"

const data = [
  {
       "foo" : "bar",
       "bar" : "sit"
  },
  {
       "foo" : "lorem",
       "bar" : "ipsum"
  },
  {
       "foo" : "dolor",
       "bar" : "amet"
  }
]
const searchKeys = ["foor", "bar"] 
const searchText = "dolor"

const results = search(data, keys, searchText)
// results: [{ "foo": "dolor", "bar": "amet" }]

answered Apr 27, 2020 at 1:47

Yann Thibodeau's user avatar

Yann ThibodeauYann Thibodeau

1,0511 gold badge12 silver badges20 bronze badges

You can use the _filter method of lodash:

return _filter((item) => item.name.includes("fo"),tempObjectHolder);

answered Jul 15, 2020 at 12:52

alfred carro's user avatar

you can use modern js with spesific key

const filter = (array, value, key) => {
          return array.filter(
            key
              ? (a) => a[key].toLowerCase().includes(value.toLowerCase())
              : (a) =>
                  Object.keys(a).some((k) =>
                    a[k].toLowerCase().includes(value.toLowerCase())
                  )
          )
        }

const data = [
    {
        "foo" : "bar",
        "bar" : "sit"
    },
    {
        "foo" : "lorem",
        "bar" : "ipsum"
    },
    {
        "foo" : "dolor blor",
        "bar" : "amet blo"
    }
];

filter(data, 'o', 'foo')
// results [{ foo: 'lorem', bar: 'ipsum' },{ foo: 'dolor blor', bar: 'amet blo' }]

answered Oct 24, 2021 at 9:35

Alauddin Afif Cassandra's user avatar

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.

Introduction

An object in JavaScript is an unordered collection of key-value pairs (key: value). Each key is known as a property, and is a string representing a property name. If a non-string is given as the key, its stringified representation will be used. A property’s value can be of any data type that fits the property conceptually — a string, a number, an array, or even a function.

An array, on the other hand, is a sorted set of values. Each value is referred to as an element, which is identified by a numerical index. An array can include values of almost any type. For example, it can store items like integers, strings, booleans, functions, etc. JavaScript arrays are also not restricted to a single type, meaning a given array can contain multiple different types within it.

When working in JavaScript, you might at a particular point in time need to determine if a key exists in a given object or array.

In this article, we will see the various methods which we could use to check if a particular key exists in a JavaScript object/array.

Using the in Operator

The in operator in JavaScript is used to determine if a certain property exists in an object or its inherited properties (also known as its prototype chain). If the provided property exists, the in operator returns true.

Checking an Object
let user = {
    name: 'John Doe',
    age: 17,
    profession: 'Farmer'
};
  
// Check if key exists
  
'name' in user; // Returns true
'profession' in user; // Returns true
'Daniel' in user; // Returns false because no key like that exists
'Farmer' in user; // Returns false because 'Farmer' is not a key, but a value
Checking an Array

Since we demonstrated that the JavaScript in operator can be used with objects, you may be asking if it can also be used with arrays. In JavaScript, everything is an instance of the Object type (except for primitives), so arrays also support the in operator.

Let’s confirm if it’s an instance of the Object type using the instanceof operator:

let numbers = [22, 3, 74, 35];
  
numbers instanceof Object // Returns true

Now, back to using the in operator:

let numbers = [12, 33, 14, 45, 6];

// Checking if index 1 is present
1 in numbers; // Returns true
// Checking if index 3 is present
3 in numbers; // Returns true

8 in numbers; // Returns false because the 8 index does exist in the array 
6 in numbers; // Returns false because the 6 index does not exist in the array

This will also return true for method properties on an array type, of which the number array is an instance.

'map' in number; // Returns true because 'map' is a method attribute of the array type

Using the hasOwnProperty() Method

In JavaScript, the hasOwnProperty() function is used to determine whether the object has the supplied property as its own property. This is important for determining if the attribute was inherited by the object rather than being its own.

Checking an Object
let user = {
    name: 'John Doe',
    age: 17,
    profession: 'Farmer'
};
  
// Check if key exists
let hasKey = user.hasOwnProperty('name'); 
  
if (hasKey) {
    console.log('This key exists.');
} else {
    console.log('This key does not exist.');
}
Checking an Array

You might begin to wonder if this would work for arrays. As we established earlier, an array is actually a prototype (instance) of the Object type, therefore it also has this method available to it.

let number = [12, 33, 14, 45];

// Check if key exists
number.hasOwnProperty(1); // Returns true
number.hasOwnProperty(0); // Returns true
number.hasOwnProperty(7); // Returns false because 7 is not an existing index on the array

Using the Object.key() Method

The static method Object.key generates and returns an array whose components are strings of the names (keys) of an object’s properties. This may be used to loop through the object’s keys, which we can then use to verify if any match a certain key in the object.

Using the some() Method

some() is a JavaScript method that tests a callback function on all the elements of the calling array and returns true if the callback function returns true for any of them.

Using some() for Objects
let user = {
    name: 'John Doe',
    age: 17,
    profession: 'Farmer'
};
  
// Check if key exists
Object.keys(user).some(key => key === 'name'); // Returns true
Object.keys(user).some(key => key === 'role'); // Returns false

We could also customize this into a reusable function:

const checkKey = (obj, keyName) => {
    let keyExist = Object.keys(obj).some(key => key === keyName);
    console.log(keyExist);
};
  
checkKey(user, 'name'); // Return true
Using some() for an Array
let number = [12, 33, 14, 45];
    
// Check if key exists
number.some(value => value === 1); // Returns true
number.some(value => value === 7); // Returns false

Again, just like with the object, we could also make use of a similar customized reusable function to check a value’s existence in an array:

const checkVal = (arr, val) => {
    let valExist = arr.some(value => value === val);
    console.log(valExist);
};

checkVal(number, 7); // Returns false
checkVal(number, 0); // Returns true
Using the indexOf() Method

JavaScript’s indexOf() method will return the index of the first instance of an element in the array. If the element does not exist then, -1 is returned.

Using indexOf() for an Object

The Object type in JavaScript does not actually support the indexOf method, since its properties/keys do not inherently have indexed positions in the object. Instead, we can get the object’s keys as an array and then check the existence of a key using the indexOf method:

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

let user = {
    name: 'John Doe',
    age: 17,
    profession: 'Farmer'
};

// Check if key exists
Object.keys(user).indexOf('name') // Returns 0
Object.keys(user).indexOf('role') // Returns -1

Keep in mind that JavaScript objects do not always preserve key order, so the index returned may not be as meaningful as in arrays. In this case, the index should primarily be used to determine just the existence of a key.

Here is an example of using this in a utility function:

const checkKey = (obj, keyName) => {
    if (Object.keys(obj).indexOf(keyName) !== -1) {
        console.log('This key exists');
    } else {
        console.log('This key does not exist');
    }
};
  
checkKey(user, 'name'); // Logs 'This key exists'
checkKey(user, 'role'); // Logs 'This key does not exists'
Using indexOf() for an Array

As we saw in the previous example, arrays do support the indexOf method, unlike objects. To use it, pass the value of the item you’re looking for to indexOf, which will then return the position of that value if it exists in the array:

let number = [12, 33, 14, 45];
    
// Find position of the item in the array
number.indexOf(14); // Returns 2
number.indexOf(7);  // Returns -1

Conclusion

In this article, we have seen all of the possible ways in which we could check if a key or item exists in a JavaScript object/array. We show how to make use of the in operator, hasOwnProperty() method, and some method. We also saw how JS objects and arrays are similar in that arrays inherit from objects, and thus contain many of the same methods.

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

Как проверить существует ли у свойства объекта искомое значение?

Есть объект:

var obiekt = {
   a:"aa",
   b:"bb",
   c:"cc"
}

Мы попробуем узнать наличие значения, которое существует в объекте, а также которого нет. Поэтому будем искать «bb» и «ff»

Решение

Мы воспользуемся конструктором Object и его методом values(), внутрь которого мы будем передавать наш объект:

Object.values(obiekt)

Данная команда вернёт нам массив со всеми значениями объекта.

["aa", "bb", "cc"]

Теперь мы можем обратиться к массиву и его методу includes() и передать в него искомые строки:

Object.values(obiekt).includes("bb")
true

Object.values(obiekt).includes("ff")
false

Вывод в консоль:

Проверили наличие значений в объекте - JavaScript

Проверили наличие значений в объекте — JavaScript

Информационные ссылки

JavaScript | Объекты (Object)

JavaScript | Массивы (Array)

Стандарт ECMAScript — Раздел «20.1.2.22 Object.values ( O )» — https://tc39.es/ecma262/#sec-object.values

Стандарт ECMAScript — Раздел «23.1.3.13 Array.prototype.includes ( searchElement [ , fromIndex ] )» — https://tc39.es/ecma262/#sec-array.prototype.includes

Массивы с буквами - JavaScript

Как разложить каждое слово в массиве, на отдельные массивы из букв? Разберём на примере: var massiv = [«efim360.ru»,»JS»,»Array»]   Для трансформаций элементов […]

ECMAScript | Оператор break

Синтаксис оператора break BreakStatement [Yield, Await] : break ; break [не LineTerminator здесь] LabelIdentifier [?Yield, ?Await] ;   14.9.1 Статическая семантика: ранние […]

ECMAScript | Встроенные функциональные объекты

Встроенные функциональные объекты (built-in function objects), определенные в этой спецификации, могут быть реализованы либо как функциональные объекты ECMAScript (10.2), поведение которых обеспечивается […]

Склонировали объект в JavaScript

Иногда в JavaScript возникает задача по клонированию какого-то объекта. И в этот момент не всегда ясно как это правильно нужно делать.   […]

Понравилась статья? Поделить с друзьями:
  • Как найти организацию в самаре
  • Как найти родственников воевавших в вов сайты
  • Забыла свой майл как найти
  • Как мне найти родственников по фамилии
  • Как найти профиль человека в спотифай