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

get the values for multiple keys

I have an array with different objects inside. I want to log the values for specific keys. If I loop on the array and if statement the key I can only get one of the values. How can I get the values of 2 keys? Take a look at the code below to understand my question better. Thanks in advance.

const testArray = [{
  "percentage": "65"
}, {
  "width": "5000",
}, {
  "length": "9000"
}]

testArray.forEach((obj) => {
  for (const [key, value] of Object.entries(obj)) {
    if (key == 'percentage') {
      //I want to log the value of key "percentage" and key "length" of different objects
      console.log(`${percentageValue}, ${lengthValue}`)
    }
  }
});

>Solution :

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

You can either have a condition for EITHER one and print whenever the condition is true, or you can have separate conditions and assign the values to variables defined outside the loop.

Here’s an example of the former case:

const testArray = [{
  "percentage": "65"
}, {
  "width": "5000",
}, {
  "length": "9000"
}]

testArray.forEach((obj) => {
  for (const [key, value] of Object.entries(obj)) {
    if (key == 'percentage' || key == 'length') {
      console.log(`${key}: ${value}`)
    }
  }
});

And here for the latter:

const testArray = [{
  "percentage": "65"
}, {
  "width": "5000",
}, {
  "length": "9000"
}]

let percentage = null;
let length = null;
testArray.forEach((obj) => {
  for (const [key, value] of Object.entries(obj)) {
    if (key == 'percentage') {
      percentage = value;
    }
    if (key == 'length') {
      length = value;
    }
  }
});
console.log(`percentage: ${percentage}, length: ${length}`)
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