I have 2 JSONs. One contains data like:
const data = {
"dataElements": {
"someField": "someData1",
"someOtherField": "someOtherData"
},
"anotherDataElement": {
"yetMoreFields": "evenMoreData",
"stillMore": "dater"
}}
The other contains something like:
const lookUp = {
"lookUpValues": {
"valueOne": "data.dataElements.someField",
"someOtherField": "someOtherData"
}}
What I need to do is take the value of lookup.lookUpValues.valueOne (which would resolve to "data.dataElements.someField") and get that value from the data object ("someData1")
JavaScript or Node.js does not provide any function to achieve your goal but you can write such a function yourself in several lines of code:
function getValue(object, path) {
// split the path in pieces separated by '.'
const pieces = path.split('.');
// walk the path, for each piece get the property with the same name from the current object
return pieces.reduce(
// result = the current object being walked
// piece = the name of the current path piece
// return the `piece` property of the `result` object (or `undefined` if it is not an object)
(result, piece) => result instanceof Object ? result[piece] : undefined,
// start walking with the provided object
object
);
}
Then call it like:
const value = getValue(data, 'dataElements.someField');
Check it online.