【问题标题】:How do you convert an array of objects into an object of object如何将对象数组转换为对象对象
【发布时间】:2022-01-23 06:15:16
【问题描述】:

我在将对象数组转换为对象对象时遇到问题。公司 API 需要这种格式的数据。任何帮助,将不胜感激。这是一个例子

原创

const array = [
 {
  type: 'ITEM',
  info: {
   item_id: 'house'
  }
 },
{
  type: 'ITEM',
  info: {
   item_id: 'house'
  }
 }
]

决赛

const array = {
 {
  type: 'ITEM',
  info: {
   item_id: 'house'
  }
 },
{
  type: 'ITEM',
  info: {
   item_id: 'house'
  }
 }
}

【问题讨论】:

  • 那不是一个有效的对象
  • 您要解决的实际问题是什么让您认为数组不够好? (如果您的数据是对象列表,那么很少有理由将其转换为具有键/值对的对象)
  • 我们的 API 需要一个对象对象作为响应。
  • 也许convert an array to object 可以提供帮助。

标签: javascript arrays object


【解决方案1】:

您必须对对象元素使用键/值对,但您可以从这个数组中创建一个对象,如下所示:

const array = [
 {
  type: 'ITEM',
  info: {
   item_id: 'house'
  }
 },
{
  type: 'ITEM',
  info: {
   item_id: 'house'
  }
 }
]

let result = {}
array.forEach((el, idx) => {
  result['data_' + idx] = el
})

console.log(result)

【讨论】:

    【解决方案2】:

    您的对象将需要密钥。 Javascript 中的对象总是 { key:value, ...} (键值对)。

    因此您需要创建这些:

    const array = [
     {
      type: 'ITEM',
      info: {
       item_id: 'house'
      }
     },
    {
      type: 'ITEM',
      info: {
       item_id: 'house'
      }
     }
    ]
    
    const obj = array.reduce((o,e,i) => { return { ...o, ['item_'+i]: e }}, {});
    
    console.log(obj);

    将“items_”更改为适合您目的的任何内容。 如果可能的话,我建议在这里使用一个数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-15
      • 2016-03-11
      • 2018-02-13
      • 1970-01-01
      • 2022-01-20
      • 2017-01-14
      相关资源
      最近更新 更多