Home > Mobile >  How to get first properties of each object in an array of objects?
How to get first properties of each object in an array of objects?

Time:11-27

const combinations = [{rolledOnes: true, scoredOnes:false}, 
                      {rolledTwos: true, scoredTwos:false}];

I am fairly new to Javascript. So, my actual array is larger than this. I want to set rolledOnes and rolledTwos to false, without affecting scoredOnes and scoredTwos. Some sort of loop or nice method would be nice?

I tried an array of arrays and can get it to function the way i want, but it is not clear compared to objects.

CodePudding user response:

We can using Array.forEach() combined with Object.keys() to do it

let combinations = [{rolledOnes: true, scoredOnes:false}, 
                      {rolledTwos: true, scoredTwos:false}];
combinations.forEach(e => {
  let k = Object.keys(e)[0]
  e[k] = false
})
 
console.log(combinations)

CodePudding user response:

Use forEach() function to loop through object

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

And keys() to get property names

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

const combinations = [
    { rolledOnes: true, scoredOnes: false },
    { rolledTwos: true, scoredTwos: false }
];

combinations.forEach(combination => {
    let property = Object.keys(combination)[0];
    combination[property] = false;
    return combination;
})

CodePudding user response:

While object key order is deterministic in ES2015 , it's better not to rely on object key order in your logic.

A safer approach might be to store the targeted keys in an array, and then use that array as a filter while iterating over your objects. This approach also better describes your actual intent and will work even in cases where the object key orders are not what you showed in the question details. For example:

const combinations = [
  {rolledOnes: true, scoredOnes: false},
  {rolledTwos: true, scoredTwos: false},
];

const falseKeys = ['rolledOnes', 'rolledTwos'];

for (const obj of combinations) {
  for (const key of falseKeys) {
    if (key in obj) obj[key] = false;
  }
}

console.log(combinations); // [ { rolledOnes: false, scoredOnes: false }, { rolledTwos: false, scoredTwos: false } ]

CodePudding user response:

const combinations = [{
    rolledOnes: true,
    scoredOnes: false
  },
  {
    rolledTwos: true,
    scoredTwos: false
  },
  {
    rolledThrees: true,
    scoredThrees: false
  },
];

combinations.forEach(comb => {
  Object.keys(comb).map(key => {
    if (key.startsWith('rolled')) {
      comb[key] = false;
    }
  })

})

console.log(combinations);

  • Related