Reputation: 83
so say i have a array and i don't know how long it is:
var arr=["first","second","final"];
and i have a object
var obj={
first:{
second:{
final:"asdf"
}
}
}
how to i make it so the when the function below is triggered, the function go through array so like it will think:
array[0] is first, ok then lets find first in object obj. arryr[1] is second, ok lets find second within first and so on) and find the value of final. but keep in mind the actual object is a lot more complex so u can't just tell me to obj[arr[0]][arr[1]][arr[2]] or anything like that.
function search(arr){
//wat here
}
Upvotes: 2
Views: 219
Reputation: 386654
You could use reduce with a default value for not given properties.
function getValue(object, array) {
return array.reduce(function (o, k) {
return (o || {})[k];
}, object);
}
var array = ["first", "second", "final"],
object = { first: { second: { final: "asdf" } } };
console.log(getValue(object, array));
console.log(getValue(object, ['a', 'b']));
Upvotes: 0
Reputation: 480
You will need a recursive function. This will get all values from a nested object in an array
function flattenObject(theObject){
var flattenedArray = [];
function walkTheObject(theObject){
for (var key in theObject){
if (theObject.hasOwnProperty(key)){
var theElement = theObject[key];
if (typeof theElement === "object"){
walkTheObject(theElement);
}else{
flattenedArray.push(theElement);
}
}
}
}
walkTheObject(theObject);
return flattenedArray;
}
Upvotes: 0
Reputation: 122057
You can use reduce()
like this.
var arr = ["first", "second", "final"];
var obj = {
first: {
second: {
final: "asdf"
}
}
}
var result = arr.reduce(function(r, e) {
return r[e]
}, obj)
console.log(result)
Upvotes: 1