Get array of values in an objects by key (supports nested objects)

PHOTO EMBED

Thu Jul 28 2022 06:09:01 GMT+0000 (Coordinated Universal Time)

Saved by @swina #javascript

//Get array of values in a object by key
//same key can be nested in an object or object with array of objects
//@object Object : Source Object
//@originalKey String : Key to be searched

const deepSearchByKey = (object, originalKey, matches = []) => {

    if(object != null) {
        if(Array.isArray(object)) {
            for(let arrayItem of object) {
                deepSearchByKey(arrayItem, originalKey, matches);
            }
        } else if(typeof object == 'object') {

            for(let key of Object.keys(object)) {
                if(key == originalKey) {
                    matches.push(object[key]);
                } else {
                    deepSearchByKey(object[key], originalKey, matches);
                }

            }

        }
    }

    return matches;
}

//Example
const myObject = {
  "users" :[
  	{
      "name" : "John"
  		"address" : {
  			"city" : "New York"
    	}
    },
    {
      "name" : "Robert"
  		"address" : {
  			"city" : "Chicago"
    	}
    }
  ]
} 

const data = deepSearchByKey ( myObject , 'city' );

console.log ( data )
//will print 
//[ "New York" , "Chicago"]
content_copyCOPY