我的目标如下:
const original = [{
"key-8": {
"some object"
}
},
{
"key-12": {
"some object"
}
},
{
"key-12": {
"some object"
}
},
{
"key-1": {
"some object"
}
},
{
"key-8": {
"some object"
}
}
]如您所见,我有两个key-8对象和两个key-12对象。我想将它们结合起来(顺序并不重要),因此输出如下:
{
{
"key-12": [{
"some object"
},
{
"some object"
}
]
}, {
"key-1": {
{
"some object"
}
},
{
"key-8": [{
"some object"
},
{
"some object"
}
]
}
}
}不管我做什么,我都不能让它起作用。我使用了reduce,我使用了常规的forEach和其他简单的“黑客”,因为TypeScript不喜欢它们。
有人能帮忙吗?
发布于 2022-09-01 14:00:26
尝尝这个
const orig = [
{
"key-8": {
"key": "...",
"value": "...",
"info": "..."
}
},
{
"key-12": {
"key": "...",
"value": "...",
"info": "..."
}
},
{
"key-12": {
"key": "...",
"value": "...",
"info": "..."
}
},
{
"key-1": {
"key": "...",
"value": "...",
"info": "..."
}
},
{
"key-8": {
"key": "...",
"value": "...",
"info": "..."
}
}
];
const result = orig.reduce(function (r, a) {
const { key, ...others } = Object.values(a)[0];
r[Object.keys(a)] = r[Object.keys(a)] || [];
r[Object.keys(a)].push(others);
return r;
}, Object.create(null));
console.log(result);
https://stackoverflow.com/questions/73570456
复制相似问题