Home > other >  Get value from object using 'Array Path'
Get value from object using 'Array Path'

Time:12-15

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.

CodePudding user response:

Not sure if this is what you were after. It's only a little update to what you have, but it provides an alternate way to detect primitives

const record = {
  firstName: "Joe Doe",
  personalData: {
    email: "[email protected]"
  }
};
const path = ["firstName", "personalData", "email"];

let primitives = ['string', 'number', 'bigint', 'boolean', 'undefined', 'symbol', 'null'];

const getJsonValueUsingPath = (rec, pa, index) => {
  let item = rec[pa[index]];
  //console.log(typeof item)
  return primitives.includes((typeof item).toLowerCase()) ? item : getJsonValueUsingPath(item, path, index   1)
}

console.log(getJsonValueUsingPath(record, path, 0));
console.log(getJsonValueUsingPath(record, path, 1));

CodePudding user response:

To simplify, you could remove the primitive-check and just assume that the path is correct and leads to the value that needs to be returned, no matter whether it is primitive or not.

Secondly, you can replace the loop with a reduce() call on the whole path, except the last item in the path.

const getValueUsingPath = (record, path) => {
    path = [...path]; // avoid mutating original path (optional)
    const last = path.pop();
    return path.reduce((record, item) => record[item], record)[last];
};

const record = {
    firstName: "Joe Doe",
    personalData: {
        email: "[email protected]"            
    }
};
const path = ["personalData","email"];

console.log(getValueUsingPath(record, path));

CodePudding user response:

lodash if you don't mind:

const _ = require('lodash');
const record = { firstName: "Joe Doe", personalData: { email: "[email protected]" } };
const path = ["personalData","email"];

_.get(record, path); // '[email protected]'
  • Related