如何将对象数组转换为 javascript 中对象的索引对象?
How to convert array of objects to indexed object of objects in javascript?
我有以下数组和一张它的结构图returns给我:
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;
}, {});
如有任何帮助或指导,我们将不胜感激。
提前谢谢你
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));
您 post 中的第一张图片(来自控制台的图片)在结构上与分配给持续连接的图片不同。
图片翻译成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;
}, {});
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;
}, {});
如有任何帮助或指导,我们将不胜感激。 提前谢谢你
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));
您 post 中的第一张图片(来自控制台的图片)在结构上与分配给持续连接的图片不同。 图片翻译成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;
}, {});