Tengo 2 JSON. Uno contiene datos como:
const data = { "dataElements": { "someField": "someData1", "someOtherField": "someOtherData" }, "anotherDataElement": { "yetMoreFields": "evenMoreData", "stillMore": "dater" }}
El otro contiene algo como:
const lookUp = { "lookUpValues": { "valueOne": "data.dataElements.someField", "someOtherField": "someOtherData" }}
Lo que debo hacer es tomar el valor de lookup.lookUpValues.valueOne (que se resolvería como "data.dataElements.someField") y obtener ese valor del objeto de datos ("someData1")
JavaScript o Node.js no proporcionan ninguna función para lograr su objetivo, pero puede escribir dicha función usted mismo en varias líneas de código:
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 ); }
Entonces llámalo como:
const value = getValue(data, 'dataElements.someField');
Compruébelo en línea .