0

I have one array which have all the properties of values for object . something like this.

var act=["name.first","age"];
var ab={name:{first:"roli",last:"agrawal"},age:24};
console.log(ab[act[0]]);

how to access value of object using act values?

Roli Agrawal
  • 2,356
  • 3
  • 23
  • 28
  • If the property names are in an array, how do you know which array item you want to use? If you want to use all of the array items, where do the results go? (Presumably not really just to the console.) – nnnnnn Mar 14 '17 at 06:19
  • i wanted to use all but for now trying with 0th element – Roli Agrawal Mar 14 '17 at 06:21
  • I've linked this to an older question that has answers covering the `"name.first"` nested properties part for one property. To access all of the properties specified in the array just do the same thing in a loop. (Another question with similar answers is [here](http://stackoverflow.com/questions/8817394/javascript-get-deep-value-from-object-by-passing-path-to-it-as-string).) – nnnnnn Mar 14 '17 at 06:24
  • I guess I should've searched before I started writing my own version of a solution that has existed for nearly six years :) – Alexander Nied Mar 14 '17 at 06:27

3 Answers3

2

You have to split the string act[0] as your object does not contain any key named "name.first":

var act=["name.first","age"];
var ab={name:{first:"roli",last:"agrawal"},age:24};
var key = act[0].split('.');
console.log(ab[key[0]][key[1]]);
Jai
  • 74,255
  • 12
  • 74
  • 103
0

try this simple

var ab = {first: 'a',
          last: 'b', 
          age: '24'}

var ac = [];
ac.push(ab);

console.log(ac[0]);   
Abhinav
  • 1,202
  • 1
  • 8
  • 12
0

Agree that it isn't natively supported, but you can use a little rectifier function to iterate down the passed path and get the value. This could probably be optimized, but works:

var act=["name.first","age"];
var ab={name:{first:"roli",last:"agrawal"},age:24};

function getProperty(inputObj, path) {

  var pathArr = path.split('.');
  var currentObjLevelOrOutput;
  var i;
  
  if (pathArr.length > 1) {
    currentObjLevelOrOutput = inputObj;
    for (i=0; i < pathArr.length; i++) {
      currentObjLevelOrOutput = currentObjLevelOrOutput[pathArr[i]];
    }
  } else {
    currentObjLevelOrOutput = inputObj[path];
  }
  
  return currentObjLevelOrOutput;

}

console.log(getProperty(ab,act[0]));
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45