【问题标题】:Returning multiple objects without key [duplicate]返回没有键的多个对象[重复]
【发布时间】:2021-11-27 21:50:16
【问题描述】:

我试图返回多个没有索引的对象,但是,我找不到使用 Objects 的方法。这是我到目前为止所尝试的,我错过了什么吗?

  const fields = [
    'name',
    'age',
    'address'
  ];

  const builtFields = []

  for (let i = 0; i < fields.length; i++) {
    builtFields.push(
      {
        [fields[i]]: { type: '' }
      }
    )
  }

  fields: Object.assign({}, builtFields)

  
  console.log(fields)

  Outputs:

  fields: {
     0: { name: { type: '' } },
     1: { age: { type: '' } },
     2: { address: { type: '' } }
  }

Desired output:

  fields: {
     name: { type: '' },
     age: { type: '' },
     address: { type: '' }
  }

【问题讨论】:

  • 小疏忽? Object.assign({}, ...builtFields)但是只要你不需要数组版本的东西,你可以直接以const builtFields = {}开头来创建最终对象。

标签: javascript


【解决方案1】:

您当前正在将数组 entries 分配给对象,而您实际上想要将每个数组 item(它是一个条目)添加到空对象:

fields: Object.assign({}, ...builtFields)

作为最短的解决方案:

const fields = [
  'name',
  'age',
  'address'
];

const obj = Object.fromEntries(fields.map(x => [x, { type: '' }]));

console.log(obj);

【讨论】:

  • 谢谢!正是我想要的
猜你喜欢
  • 1970-01-01
  • 2018-10-18
  • 2015-10-11
  • 2018-01-02
  • 2017-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
相关资源
最近更新 更多