Search code examples
javascriptobject

How to get value from an object searched key is in string


I have an object

const lead = {
  companies: [{
    schoolName: "ABC",
    education: "Graduation"
  }, {
    schoolName: "DEF",
    education: "Graduation2"
  }],
  hello: 'world',
  education: {
    graduation: 'true',
  },
  nameArray: ['hello', 'world']
}

Variable I am getting from frontend

'companies[0].schoolName'

I just have to send the value if it exists in the object


Solution

  • Here is a generic solution to walk the path of an object to get its value, or null if it does not exist:

    const lead = {
      companies: [
        { schoolName: "ABC", education: "Graduation" },
        { schoolName: "DEF", education: "Graduation2" }
      ],
      hello: 'world',
      education: {
        graduation: 'true',
      },
      nameArray: ['hello', 'world']
    };
    
    function getValue(obj, path) {
      return path
      .split(/[.\[\]]/)       // split on delimiters
      .filter(Boolean)        // filter out empty items
      .reduce((acc, key) => { // reduce obj: walk the path
        acc = acc ? acc[key] : null;
        return acc;
      }, obj);
    }
    
    [
      'companies[0].schoolName',
      'companies[1].education',
      'hello',
      'does.not.exist'
    ].forEach(path => {
      let value = getValue(lead, path);
      console.log(path, '==>', value);
    });

    Output:

    companies[0].schoolName ==> ABC
    companies[1].education ==> Graduation2
    hello ==> world
    does.not.exist ==> null