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))