gpt4 book ai didi

javascript - 在 JavaScript 中从数组到复杂的字符串格式

转载 作者:行者123 更新时间:2023-11-30 11:02:35 25 4
gpt4 key购买 nike

我目前有一个返回这个数组的函数:

var myArray = [
{ Sepal_Width: { Average_Sepal_Width: series => series.average() } },
{ Sepal_Width: { Sum_Sepal_Width: series => series.sum() } },
{ Petal_Length: { Average_Petal_Length: series => series.average() } }
]

但我需要输出看起来像这样:

Sepal_Width: { 
Average_Sepal_Width: series => series.average(),
Sum_Sepal_Width: series => series.sum()
},
Petal_Length: {
Average_Petal_Length: series => series.average()
}

我只是想知道这是否可能,因为我需要考虑到用户向原始数组添加额外的行,例如 { Petal_Length: Sum_Petal_Length: series => series.sum() }} 并让它自动进入 Petal_Length:{}。

Sepal_Width: { 
Average_Sepal_Width: series => series.average(),
Sum_Sepal_Width: series => series.sum()
},
Petal_Length: {
Average_Petal_Length: series => series.average() },
Sum_Petal_Length: series => series.sum() }
}

最佳答案

您可以获得第一个键并将值分配给结果对象中的给定键。

var array = [{ Sepal_Width: { Average_Sepal_Width: series => series.average() } }, { Sepal_Width: { Sum_Sepal_Width: series => series.sum() } }, { Petal_Length: { Average_Petal_Length: series => series.average() } }],
result = array.reduce((r, o) => {
Object.entries(o).forEach(([k, v]) => Object.assign(r[k] = r[k] || {}, v));
return r;
}, {});

console.log(result);

关于javascript - 在 JavaScript 中从数组到复杂的字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57082287/

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