CodeMonkey CodeMonkey - 6 months ago 17
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": [
"item1",
"item2"
]
}, {
"product2": [
"item1",
"item2"
]
}, {
"product3": [
"item5",
"item6"
]
}]
}
}


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

"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"]

Explanation:
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.