CodeMonkey CodeMonkey - 2 years ago 136
JSON Question

Finding JSON Array Object Values by KeyName

I am looking for a HashMap sort of implementation in Javascript for JSON for the following case.

I have the JSON with following structure:

"level1": {
"level2": [{
"product1": [
}, {
"product2": [
}, {
"product3": [

For my use case, I get a value , say 'product3', I want to find values for this key i.e "item5", "item6". I have a way, that i can loop through the entire level2 object but want to know if I can simply use key to find values.

Answer Source

"One-line" optimized solution using Array.some, Array.indexOf and Object.keys functions (no need to iterate through all "product" objects):

// json is your initial object
var key = 'product3', values;
json['level1']['level2'].some((v) => Object.keys(v).indexOf(key) !== -1 && (values = v[key]), values);

console.log(values);  // ["item5", "item6"]

arr.some(callback[, thisArg]) - This function returns true if the callback function returns a truthy value for any array element; In my example values becomes thisArg parameter which should contain values of the desired "keyName".
It will iterate through all "product" objects, but will stop looping immediately if the required keyName is found amoung the properties of the current object ( Object.keys(v).indexOf(key) !== -1 ).
As a concurrent condition it should save the values of found object which can be achieved with truthy assignment expression && (values = v[key]).
That's all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download