gpt4 book ai didi

javascript - 如何将具有相同键的对象数组分组为单个数组中的对象?

转载 作者:行者123 更新时间:2023-12-02 13:52:52 25 4
gpt4 key购买 nike

我的数组是

[Object { Color="Blues",  Shape="Octagon",  Thickness="High (Over 1 Inch)",  more...}, Object { Color="Burgundys",  Shape="Oval",  Thickness="3⁄8" (approx.)",  more...}]

我想要输出:

[{"Color":["Blues","Burgundys "],"Shape":['Octagon',"Oval"]}] 

其他值也一样

最佳答案

我会通过迭代每个对象的键并将键作为哈希添加到值对象中来解决此问题。

var vals = {}
var src = [{ Color="Blues", Shape="Octagon", Thickness="High (Over 1 Inch)"}, { Color="Burgundys", Shape="Oval", Thickness="3⁄8 (approx.)"}]

src.forEach( function( obj ){

for( var key in obj ){
if( vals[ key ] === undefined )
vals[ key ] = []

vals[ key ].push( obj[ key ])
}

})

关于javascript - 如何将具有相同键的对象数组分组为单个数组中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40895569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com