【问题标题】:How to convert array of objects to indexed object of objects in javascript?如何在javascript中将对象数组转换为对象的索引对象?
【发布时间】:2020-07-28 15:09:35
【问题描述】:

我有以下数组以及它的结构如何返回给我的图片:

const connections = [1:{fromBox: 0, fromConnector: "port_0", toBox: 1, toConnector: "port_0"},
                     1:{fromBox: 0, fromConnector: "port_1", toBox: 1, toConnector: "port_1"}
                    ]

并且我需要创建一个具有此结构的对象以与我的代码兼容:

"connections": {
    "0": {
      "fromBox": "0",
      "fromConnector": "port_0",
      "toBox": "1",
      "toConnector": "port_0",
    },
    "1": {
      "fromBox": "0",
      "fromConnector": "port_1",
      "toBox": "1",
      "toConnector": "port_1"
    }
  }

看到类似的疑问,我已经明白,使用归约方法我应该能够实现它,但是当尝试将它们在数组中的索引放入对象时,它给了我就好像数组的元素一样未定义

      const connectionsKeys = Object.keys(connections);

      const result = connections.reduce((c, v) => {
        c[v.connectionsKeys] = c[v.connectionsKeys] || {}; 

        return c;
      }, {});

任何帮助或指导将不胜感激。 提前谢谢你

【问题讨论】:

  • connections 不是有效数组。
  • @palaѕн 数组由数据库返回给我

标签: javascript arrays object indexing arrayobject


【解决方案1】:

const connections = [{fromBox: 0, fromConnector: "port_0", toBox: 1, toConnector: "port_0"},
                     {fromBox: 0, fromConnector: "port_1", toBox: 1, toConnector: "port_1"}
                    ]


function convertToObject(arr){
  return Object.assign({},arr)
}

console.log(convertToObject(connections));

【讨论】:

    【解决方案2】:

    您帖子中的第一张图片(来自控制台的那张)在结构上与分配给恒定连接的图片不同。 图片翻译成js代码应该是这样的

    const connections = [{1:{fromBox: 0, fromConnector: "port_0", toBox: 1, toConnector: "port_0"}},
                     {1:{fromBox: 0, fromConnector: "port_1", toBox: 1, toConnector: "port_1"}}
                    ]
    

    从这个结构中,您可以进行以下归约,最终得到您需要的结构:

    const result = connections.reduce((acc, curr, index) => {
        acc[index] = curr['1'];
    
        return acc;
      }, {});
    

    【讨论】:

    • 谢谢,原来的结构是上一个函数的错误,我已经更正了,但我从你的解决方案中注意到了,因为我不知道如何更正它!! @回答非常感谢
    猜你喜欢
    • 2017-01-14
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 2019-10-22
    • 2022-01-23
    • 2013-11-21
    相关资源
    最近更新 更多