Anon-aq
Anon-aq

Reputation: 3

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

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.

Upvotes: 0

Views: 718

Answers (4)

Salwa A. Soliman
Salwa A. Soliman

Reputation: 746

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

Upvotes: 0

flyingfox
flyingfox

Reputation: 13506

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)

Upvotes: 1

jsejcksn
jsejcksn

Reputation: 33921

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 } ]

Upvotes: 0

Slidein
Slidein

Reputation: 319

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

Upvotes: 0

Related Questions