Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Handling object with keys correctly on ForEach

I have this object, where I am using forEach method to loop thru the key values and display the object content in a table. Currently, it works fine, but if i try to alter the keys name array, the forEach loop will break:

let response = [{
  "rule.id": 222222,
  "rule.name": "Test Name",
  "rule.compiledlimitation": "Sampel Data",
  "rule.target": "TEST_ID",
}]

let keys = ["id", 'name', "compiledlimitation", 'target']

keys.forEach(key => {
  this.allData.push({
    name: key,
    row2: response[0][`rule.${key}`]
  })
});

The problem happens when i try to modify the keys values, For example if i want to enter ID as caps, or name as ‘Name’, or compiledlimitations as ‘Compiled Limitations’ then my loop will break because it doesn’t match the object name.

This is how the table looks if i alter the keys name, the value is empty 🙁
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What would be the right way to do this?

>Solution :

You could just extend your keys array and bind a custom label to each key:

let response = [
  {
    'rule.id': 222222,
    'rule.name': 'Test Name',
    'rule.compiledlimitation': 'Sampel Data',
    'rule.target': 'TEST_ID',
  },
];

let keys = [
  { key: 'id', label: 'ID' },
  { key: 'name', label: 'Name' },
  { key: 'compiledlimitation', label: 'Compiled Limitation' },
  { key: 'target', label: 'Target' },
];

allData = [];

keys.forEach(({ key, label }) => {
  allData.push({
    name: label, // use the label that will get displayed
    row2: response[0][`rule.${key}`], // use the key to get the info
  });
});

console.log(allData);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading