Home > Blockchain >  accessing object property dynamically from array of strings [duplicate]
accessing object property dynamically from array of strings [duplicate]

Time:09-23

I am trying to access an object property dynamically from an array of strings (the have the path of the needed value)! it seems it access only the first index(Properties) but the others in undefine I am expecting the result to be "ES_STUE".

let objPath = ["properties.Constraints.Level"];

const object = {
  properties: {
    Visibility: {
      "Tender Code": "",
    },
    Data: {
      DTU_ClassificationNumber: "",
      DTU_InformationAccuracy: "",
    },
    "Model Properties": {
      "Workset (Manual)": "No",
    },
    Constraints: {
      Level: "ES_STUE",
      Host: "Level : ES_STUE",
      "Offset from Host": "0.000 mm",
      "Moves With Nearby Elements": "No",
      "Default Elevation": "0.000 mm",
    },
  },
};

for (const iterator of objPath) {
  const keySigment = iterator.split(".");
  for (const prop of keySigment) {
    console.log(prop);
    const result = object[prop];
    //const result = object["Properties"]["Constraints"]["level"]  not sure if this is correct
    console.log(result); // the result should be "ES_STUE"
  }
}

CodePudding user response:

Logic

  • Split the objPath string.
  • Loop through the split array
  • Each time while looping update the result node with result[prop] where prop is the key.
  • This will drill down the object as itration.

let objPath = ["properties.Constraints.Level"];

const object = {
  properties: {
    Visibility: {
      "Tender Code": "",
    },
    Data: {
      DTU_ClassificationNumber: "",
      DTU_InformationAccuracy: "",
    },
    "Model Properties": {
      "Workset (Manual)": "No",
    },
    Constraints: {
      Level: "ES_STUE",
      Host: "Level : ES_STUE",
      "Offset from Host": "0.000 mm",
      "Moves With Nearby Elements": "No",
      "Default Elevation": "0.000 mm",
    },
  },
};

for (const iterator of objPath) {
  const keySigment = iterator.split(".");
  let result = object;
  for (const prop of keySigment) {
    console.log(prop);
    result = result[prop];
    console.log(result); // the result should be "ES_STUE"
  }
}

  • Related