1

I am trying to access a property of an object which is within an object in an array. Quite the mouthful. The catch is that I want to do this using a variable. Its probably easier if i explain with code;

var array= [
  { id: 0, client: { id:0, clientName: "John" }},
  { id: 1, client: { id:1, clientName: "Tom" }}
]
console.log(array[0][client][clientName]); // Displays correctly

So the above code works as expected using the brackets notation. But as I said earlier I need to use a Variable like this example;

var array= [
  { id: 0, client: { id:0, clientName: "John" }},
  { id: 0, client: { id:0, clientName: "John" }}
]
var property = "client.clientName";
console.log(array[0][property]); // Does not work

I understand why this code wouldn't work but really this is more of a pseudo code to explain what I am trying to achieve!

3 Answers3

1

var array= [
  { id: 0, client: { id:0, clientName: "John" }},
  { id: 0, client: { id:0, clientName: "John" }}
]
var property = "client.clientName",
    getPropByString=function(data,val){
      val=val.split(/\./g);
      var dataApp=data;
      val.forEach(function(prop){
        dataApp=dataApp[prop];
      });
      return dataApp;
    };
console.log(getPropByString(array[0],property));
LellisMoon
  • 4,810
  • 2
  • 12
  • 24
1

That you can't get it like that way instead split and get nested properties. Use Array#reduce method to get the nested property by splitting the property string using String#split method.

// split the string and iterate over the result array
property.split('.').reduce(function(o, p) {
  // check object defined and return nested property value
  return o && o[p];
  // set initial value as the object where you need to fetch data
}, array[0])

var array = [{
  id: 0,
  client: {
    id: 0,
    clientName: "John"
  }
}, {
  id: 0,
  client: {
    id: 0,
    clientName: "John"
  }
}]

var property = "client.clientName";
console.log(
  property.split('.').reduce(function(o, p) {
    return o && o[p];
  }, array[0])
);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

You could use a function, which splits the string with the property names and reduce the given object.

function getValue(object, path) {
    return path.split('.').reduce(function (o, k) {
        return (o || {})[k];
    }, object);
}

var array = [{ id: 0, client: { id:0, clientName: "John" } }, { id: 1, client: { id:1, clientName: "Tom" } }],
    property = "client.clientName";

console.log(getValue(array[0], property));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392