js中使用reduce将json数组 转换为json

1.使用reduce:

let arr = [{
"code": "badge",
"priceList": [{
"amount": 3000
}]
},

{
"code": "DigitalPhoto",
"priceList": [{
"amount": 1990
}]
}
]

let arr2 = arr.reduce((pre,cur)=>{
pre[cur.code] = cur.priceList
return pre
},{})
console.log(arr2)

打印结果:

{ badge: [ { amount: 3000 } ],
DigitalPhoto: [ { amount: 1990 } ] }

2.使用map:

var kvArray = [{key: 1, value: 10},
{key: 2, value: 20},
{key: 3, value: 30}];

var reformattedArray = kvArray.map(function(obj) {
var rObj = {};
rObj[obj.key] = obj.value;
return rObj;
});

// reformattedArray 数组为: [{1: 10}, {2: 20}, {3: 30}],

猜你喜欢

转载自www.cnblogs.com/qiyc/p/9288512.html
今日推荐