我有一个像这样的对象数组:
[
{
"dow": 0,
"min_price": 2000,
"max_price": 4000,
"is_enable": true
},
{
"dow": 1,
"min_price": 500,
"max_price": 3000,
"is_enable": true
},
{
"dow": 2,
"min_price": 500,
"max_price": 3000,
"is_enable": true
},
{
"dow": 3,
"min_price": 1000,
"max_price": 3000,
"is_enable": true
}
]
我怎样才能把它变成这样的东西?订单无关紧要。
{
advancePrice_0_max: 4000,
advancePrice_0_min: 2000,
advancePrice_1_max: 3000,
advancePrice_1_min: 500,
advancePrice_2_max: 3000,
advancePrice_2_min: 500,
advancePrice_3_max: 3000,
advancePrice_3_min: 500
..
..
}
我试图从这开始,但即使在代码下面也有snytax错误。
let temp = {};
if (!isEmpty.custom_pricing) {
temp = custom_pricing.map(obj => {
`advancePrice_${obj.dow}_min`: obj.min_price,
`advancePrice_${obj.dow}_max`: obj.max_price
})
console.log(temp);
}
但是我被困住了,不知道如何继续......
答案 0 :(得分:1)
您希望将数组缩减为单个对象,因此:
var result = data.reduce(function (acc,el,i) {
acc['advancedprice_' + i + '_max'] = el.max_price;
acc['advancedprice_' + i + '_min'] = el.min_price;
return acc;
}, {});
答案 1 :(得分:0)
您有两种选择:
我建议你使用别人的解决方案,因为你不必重新发明轮子。这个答案是详尽无遗的例子:Fastest way to flatten / un-flatten nested JSON objects,这里有一个在线示例:http://fiddle.jshell.net/blowsie/S2hsS/show/light/
请参阅以下代码段:
JSON.flatten = function (data) { ...
和
JSON.unflatten = function (data) {
答案 2 :(得分:0)
使用forEach
因为您希望结果不是数组格式的对象,如果您使用map,则temp将是一个包含返回数据的数组。
使用它:
let temp = {};
if (!isEmpty.custom_pricing) {
custom_pricing.forEach(obj => {
temp[`advancePrice_${obj.dow}_min`] = obj.min_price;
temp[`advancePrice_${obj.dow}_max`] = obj.max_price;
})
console.log(temp);
}
检查工作代码段:
let custom_pricing = [{
"dow": 0,
"min_price": 2000,
"max_price": 4000,
"is_enable": true
},
{
"dow": 1,
"min_price": 500,
"max_price": 3000,
"is_enable": true
},
{
"dow": 2,
"min_price": 500,
"max_price": 3000,
"is_enable": true
},
{
"dow": 3,
"min_price": 1000,
"max_price": 3000,
"is_enable": true
}
]
let temp = {};
custom_pricing.forEach(obj => {
temp[`advancePrice_${obj.dow}_min`] = obj.min_price;
temp[`advancePrice_${obj.dow}_max`] = obj.max_price;
})
console.log(temp);
答案 3 :(得分:0)
您可以使用旧的for
循环...
let arr = [
{
"dow": 0,
"min_price": 2000,
"max_price": 4000,
"is_enable": true
},
{
"dow": 1,
"min_price": 500,
"max_price": 3000,
"is_enable": true
},
{
"dow": 2,
"min_price": 500,
"max_price": 3000,
"is_enable": true
},
{
"dow": 3,
"min_price": 1000,
"max_price": 3000,
"is_enable": true
}
];
let res = {};
for (let i = 0; i < arr.length; i++) {
res[`advancePrice_${i}_max`] = arr[i].max_price;
res[`advancePrice_${i}_min`] = arr[i].min_price;
}
console.log(res);
&#13;