That would simply be done by the invention of a "reusable" Object method. I call it Object.prototype.getNestedValue()
It dynamically fetches the value resides at deeply nested properties. You have to provide the properties as arguments in an ordered fashion. So for example if you would like to get the value of myObj.testable.some.id
you should invoke the function as var myId = myObj.getNestedValue("testable","some","id") // returns 10
So lets see how it works.
Object.prototype.getNestedValue = function(...a) {
return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
var myObj = {
testable: {
some: {
id: 10
},
another: {
some: {
id: 20
}
},
an : {
arrayExample: ['test']
}
}
},
myId = myObj.getNestedValue("testable","some","id");
console.log(myId);
//or if you receive the properties to query in an array can also invoke it like
myId = myObj.getNestedValue(...["testable","some","id"]);
console.log(myId);
So far so good. Let's come to your problem. Once we have this nice tool in our hand what you want to do becomes a breeze. This time i insert your each query in an array and the spread operator is our friend. Check this out.
Object.prototype.getNestedValue = function(...a) {
return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
var myObj = {
testable: {
some: {
id: 10
},
another: {
some: {
id: 20
}
},
an : {
arrayExample: ['test']
}
}
},
idCollection = [["testable","some","id"],["testable","another","some","id"],["testable","an","arrayExample",0]],
ids = idCollection.reduce((p,c) => p.concat(myObj.getNestedValue(...c)),[]);
console.log(ids);
Of course the the argument we use for querying can be dynamic like
var a = "testable",
b = "another",
c = "some",
d = "id",
myId = myObj.getNestedValue(a,b,c,d);
and you can reuse this Object method everywhere including arrays since in JS arrays are objects and the have perfect access to the Object.prototype
. All you need is to pass the index of the array instead of the property of an object.