1

I'm wondering if there is a way to dynamic get children objects dynamically using strings:

Ex: "industry.description"

var fields = [{
    id: "1",
    industry: {
      description: "Test Industry1"
    }
  },
  {
    id: "2",
    industry: {
      description: "Test Industry2"
    }
  }
  ];

  var field1 = "id";
  var field2 = "industry.description";

  var val1 = fields[0][field1];
  var val2 = fields[0][field2]; // How can I get 'Test Industry1' here?

  console.log(val1);
  console.log(val2);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Kevin Jensen
  • 1,418
  • 3
  • 18
  • 25

4 Answers4

2

Either do:

fields[0]["industry"]["description"];

Or separate it into multiple fields (e.g. [field2][field3] where field2 = "industry" and field3 = "description").

Or, use reduce to work with your current string:

var val2 = field2.split(".").reduce((o, k) => o[k], fields[0]);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

The "industry.description" key will not work. What you need is to first get the object under the "industry" key and then get the "description" from it. Like this:

fields[0]["industry"]["description"] // "Test Industry1"
1

A simple solution that allows a nested value to be extracted from an object by a dynamically supplied path would be:

function getValue(object, path) {

  // Break input path into parts separated by '.' via split
  const parts = path.split(".");

  // Iterate the parts of the path, and reduce that parts array to a single
  // value that we incrementally search for by current key, from a prior
  // nested "value"
  return parts.reduce((value, key) => value ? value[key] : value, object)  
}

console.log(getValue(fields[0], "industry.description")); // Test Industry1

The nice thing about this is that it's simple and doesn't require another library to be added to your project. Here's how it works in context of your code:

function getValue(object, path) {
  
  const parts = path.split(".");
  
  return parts.reduce((value, key) => value ? value[key] : value, object)  
}

var fields = [{
    id: "1",
    industry: {
      description: "Test Industry1"
    }
  },
  {
    id: "2",
    industry: {
      description: "Test Industry2"
    }
  }
];

var field1 = "id";
var field2 = "industry.description";

console.log(getValue(fields[0], field1))
console.log(getValue(fields[0], field2))
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
0
var fields = [{
    id: "1",
    industry: {
      description: "Test Industry1"
    }
  },
  {
    id: "2",
    industry: {
      description: "Test Industry2"
    }
  }
  ];

  var field1 = "id";
  var field2 = "industry";
  var subField2 = "description"

  var val1 = fields[0][field1];
  var val2 = fields[0][field2][subField2]; // How can I get 'Test Industry1' here?

  console.log(val1);
  console.log(val2);