Skip to content

Instantly share code, notes, and snippets.

@jherax
Last active May 30, 2020 15:41
Show Gist options
  • Save jherax/8dd257d5c4159c9b6df4 to your computer and use it in GitHub Desktop.
Save jherax/8dd257d5c4159c9b6df4 to your computer and use it in GitHub Desktop.
Gets the first value associated to an object's property
/**
* Gets the first value associated to an object's property.
* Can go recursively through objects and arrays.
*
* @param {Object | Array} obj: the object or array to look for the property/index value
* @param {String | Number} key: the object's property name or array index
* @return {Any}
*/
function getValueByKey(obj, key) {
let value;
for (const prop in obj) {
if (prop == key) return obj[prop];
if (obj[prop] instanceof Object) {
value = getValueByKey(obj[prop], key);
if (value !== undefined) return value;
}
}
}
var obj = {
a: "value:a",
b: {"inner-b": "coco"},
c: {"inner-c": "liso", data: {"#text": "test", depth: 3}},
d: "value:d",
};
obj.P = [
{b: {data: {values: {":clientId": 501}}}},
{b: {data: {values: {":clientId": 777}}}}
];
getValueByKey(obj, "b"); //{"inner-b": "coco"}
getValueByKey(obj, "data"); //{"#text": "test", depth: 3}
getValueByKey(obj, "values"); //{":clientId": 501}
getValueByKey(obj, ":clientId"); //501
var list = [
'zero',
'one',
'two',
[45, 76, 23, 87, 90],
];
var index = 2;
getValueByKey(list, index); //"two"
getValueByKey(list, 3); //[...]
getValueByKey(list, 4); //90
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment