gpt4 book ai didi

javascript - 嵌套的键值对分组到一个数组中

转载 作者:行者123 更新时间:2023-12-05 09:07:15 26 4
gpt4 key购买 nike

我有一个带有嵌套键值对的对象:

Products:{
Clip:{
today_entry: 0,
today_sold: 0
},
Necklace:
{
today_entry: 0,
today_sold: 2
}
}

我想遍历 Objects Clip ad Necklace 并根据它们的内部键(即 today_entry、today_sold)将值分组为以下格式:

{
today_entry : [0,0],
today_sold : [0,2]
}

我尝试使用 Object.entries 进行操作,但由于它是嵌套的,所以我无法获取内部键。谁能帮帮我?谢谢。

最佳答案

你可以使用reudce:

const products = {
Clip:{
today_entry: 0,
today_sold: 0,
},
Necklace:
{
today_entry: 0,
today_sold: 2,
},
};

const result = Object.keys(products).reduce((ac, key) => ({
today_entry: [ ...ac.today_entry, products[key].today_entry],
today_sold: [ ...ac.today_sold, products[key].today_sold],
}), { today_entry: [], today_sold: []});

console.log(result);

如果数组中值的顺序很重要,您还应该按照您想要的方式对键进行排序。

关于javascript - 嵌套的键值对分组到一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65195904/

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