I need to extract a value from a record using a path defined in a Array of strings. I came up with the following solution. It works, but this code seems a little bit too complicated to understand, in my opinion. I'd like to know if is there a better way to check if a value is a primitive type and if anyone can think in a simpler way to do the job.
const record = {
firstName: "Joe Doe",
personalData: {
email: "[email protected]"
}
};
const path = ["personalData","email"];
const getJsonValueUsingPath = (record, path, index) => {
const isPrimitiveType =
Object(record[path[index]]) !== record[path[index]];
if (isPrimitiveType) {
return record[path[index]];
} else {
return getColumnValue(record[path[index]], path, index + 1);
}
};
I need this function because I'm using a Third Party lib that requires such functionality. Please don't say it's a bad idea to extract an object property value using an array of strings.
jsontag. This is not about JSON. There is no JSON in your question. I removed it from your question.const query = (ps) => (obj) => ps .reduce ((a, p) => (a || {}) [p], obj).