javascript 如何获取对象数组中每个对象的第一个属性?

7xllpg7q  于 2022-11-27  发布在  Java
关注(0)|答案(3)|浏览(301)
const combinations = [{rolledOnes: true, scoredOnes:false}, 
                      {rolledTwos: true, scoredTwos:false}];

我对Javascript还是个新手。所以,我的实际数组比这个大。我想把rolledOnes和rolledTwos设置为false,而不影响scoredOnes和scoredTwos。某种循环或函数会很好吗?
我尝试了数组的数组,可以让它按照我想要的方式运行,但与对象相比并不清楚。

dly7yett

dly7yett1#

我们可以使用Array.map()结合Object.keys()来实现

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

xxls0lw82#

使用forEach()函数遍历对象
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
keys()以获取属性名称
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;
})
pxy2qtax

pxy2qtax3#

虽然对象键顺序在ES2015+中是确定的,但最好不要依赖逻辑中的对象键顺序。
更安全的方法是将目标键存储在数组中,然后在迭代对象时将该数组用作筛选器。例如:

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

相关问题