如何将对象数组映射到某个字段聚集/讨人喜欢的不同数组?
我已经有一系列的对象:
[
{
"n": "David",
"t": 1,
"o": "2"
},
{
"n": "Paul",
"t": 3,
"o": "4"
},
{
"n": "David",
"t": 5,
"o": "6"
},
{
"n": "David",
"t": 7,
"o": "8"
},
{
"n": "Paul",
"t": 9,
"o": "10"
}
]
我需要映射到以下内容:
[
[
"David",
[
[1, "2"],
[5, "6"],
[7, "8"]
]
],
[
"Paul",
[
[3, "4"],
[9, "10"]
]
]
]
因此,基本上是一个数组,其中每个内部数组是“ the field ” n“ n”
字段的“组”,所有元素汇总了成为阵列。
I've this array of objects:
[
{
"n": "David",
"t": 1,
"o": "2"
},
{
"n": "Paul",
"t": 3,
"o": "4"
},
{
"n": "David",
"t": 5,
"o": "6"
},
{
"n": "David",
"t": 7,
"o": "8"
},
{
"n": "Paul",
"t": 9,
"o": "10"
}
]
And I need to map to this:
[
[
"David",
[
[1, "2"],
[5, "6"],
[7, "8"]
]
],
[
"Paul",
[
[3, "4"],
[9, "10"]
]
]
]
So basically an array of array, where each inner array is a "group by" the field "n"
field and all elements aggregated become arrays.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
降低
的通常解决方案。组成n
,并使用object.values
进行对象的值或使用循环的
The usual solution using
reduce
. Group by then
and the take the values of object usingObject.values
or using a
for of
loop要获取输出,请使用对象将存储的映射数组的索引存储在名称中。 [例如,大卫是0,对于保罗来说,是1]。
我们可以在数组中使用字符串索引来可读目的,但我认为这不是一个好主意,因为输出模式并不那么复杂。
To get the output, use object to store the index of the stored mapped array with name. [e.g. for David, it's 0 and for Paul, it's 1].
We can use string Index in the array for the readable purpose but I don't think that's a great idea as output schema is not that complex.
您可以使用
array.Reduce
和object.entries
进行操作。you can do it using
Array.reduce
andObject.entries
从数据中制作一个字典,然后将结果以所需的格式放置。
Make a dictionary out of the data and then put the result in the desired format.