gpt4 book ai didi

javascript - 使用 Javascript 从 Json 中的子元素创建新键

转载 作者:行者123 更新时间:2023-11-30 11:10:20 24 4
gpt4 key购买 nike

我想使用 ES6/ES5 从 json 中的子值创建新键。我尝试使用箭头函数,但无法得到结果。首先你可以在下面看到我的 json 部分,

[  
{
matchId:307,
matchStatusId:5,
matchHomeScore:0,
matchAwayScore:0,
matchTime:0,
homeClubId:608,
homeClub:{
clubId:608,
clubName:"Annaba"
},
awayClubId:609,
awayClub:{
clubId:609,
clubName:"Bazer Sakhra"
},
leagues:[
{
leagueId:65,
parentLeagueId:null,
leagueName:"ALGERIA"
},
{
leagueId:66,
parentLeagueId:65,
leagueName:"Algeria Cup"
}
]
},
]

我想创建新的父 key 。它将从子项的值中获取值并将其合并。子项编号可变。不是每次 2 项。leaguesGeneral:"ALGERIA - Algolia 杯"

   leaguesGeneral:"ALGERIA - Algeria Cup"   
leagues: [
{
leagueId:65,
parentLeagueId:null,
leagueName:"ALGERIA"
},
{
leagueId:66,
parentLeagueId:65,
leagueName:"Algeria Cup"
}
]

我找到了这个方法。但它结合了父级的所有内容。

data = data.map(function (x) {
var keys = Object.keys(x);
x.newKeyValue = keys.map(key => x[key]).join('-');
return x;
});

最佳答案

leaguesGeneral 键可以添加到数组中的每个对象,使用

o.leagues.map(({ leagueName }) => leagueName).join(' - ')

const data = [  
{
matchId:307,
matchStatusId:5,
matchHomeScore:0,
matchAwayScore:0,
matchTime:0,
homeClubId:608,
homeClub:{
clubId:608,
clubName:"Annaba"
},
awayClubId:609,
awayClub:{
clubId:609,
clubName:"Bazer Sakhra"
},
leagues:[
{
leagueId:65,
parentLeagueId:null,
leagueName:"ALGERIA"
},
{
leagueId:66,
parentLeagueId:65,
leagueName:"Algeria Cup"
}
]
},
];

const result = data.map(o => {
if (o.leagues) {
o.leaguesGeneral = o.leagues.map(({ leagueName }) => leagueName).join(' - ');
}
return o;
})

console.log(result)

关于javascript - 使用 Javascript 从 Json 中的子元素创建新键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53954719/

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