Home > Back-end >  get the values for multiple keys
get the values for multiple keys

Time:07-05

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}`)
    }
  }
});

CodePudding user response:

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}`)

  • Related