eclipseIzHere
eclipseIzHere

Reputation: 83

How to get everything within an array and assign it to a variable with a space in between as a string

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

Answers (3)

Nina Scholz
Nina Scholz

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

Michael Westcott
Michael Westcott

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

Nenad Vracar
Nenad Vracar

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

Related Questions