Javascript 遍历嵌套的对象并返回转换和重命名的对象数组



我已经查看了有关嵌套对象的所有可用答案,但到目前为止没有一个帮助。 我确实有一个深层嵌套对象,例如:

let datastat = 
{
"statisticData": {
"lastStatisticOne": {
"min": 0,
"max": 10
},
"lastStatisticTwo": {
"min": 0,
"max": 20
},
"firstStatisticOne": {
"min": 0,
"max": 30,
},
"firstStatisticTwo": {
"min": 0,
"max": 40,
},
},
"statisticValue": [
none important Data
]
}

我试图实现的是:

statisticNew =
[
{
"lastStatisticOne": [{ "name": "min", "value": 0 }, { "name": "max", "value": 10 }]
},
{
"lastStatisticTwo": [{ "name": "min", "value": 0 }, { "name": "max", "value": 20 }]
},
{
"firstStatisticOne": [{ "name": "min", "value": 0 }, { "name": "max", "value": 30 }]
},
{
"firstStatisticTwo": [{ "name": "min", "value": 0 }, { "name": "max", "value": 40 }]
}
]

我的尝试失败了:

const statistic = [];
statistic.push(datastat.statisticData);
for(let item in statistic){
if (statistic.hasOwnProperty(item)) {
const result = Object.keys(statistic[0]).map(e => ({name: e, value: statistic[0][e]}));
console.log(result);
}
}

如何获得正确的输出?

这应该可以做到:

let datastat = {
"statisticData": {
"lastStatisticOne": {
"min": 0,
"max": 10
},
"lastStatisticTwo": {
"min": 0,
"max": 20
},
"firstStatisticOne": {
"min": 0,
"max": 30,
},
"firstStatisticTwo": {
"min": 0,
"max": 40,
},
}
}
let newStat = Object.keys(datastat.statisticData).reduce((acc, key) => {
let vals = Object.entries(datastat.statisticData[key]).map(([key, val]) => ({
name: key,
value: val
}))
acc.push({
[key]: vals
});
return acc;
}, []);

您可以遍历 dataStat 的键并获得预期的输出,如下所示:

let statisticNew = [];
Object.keys(datastat['statisticData']).map(function (item) {
let stat_obj = {};
let temp_arr  = [];
let inner_dict = datastat['statisticData'][item];
Object.keys(inner_dict).map(function (inner_item) {
let temp_obj = {};
temp_obj['name'] = inner_item;
temp_obj['value'] = inner_dict[inner_item];
temp_arr.push(temp_obj)
});
stat_obj[item] = temp_arr;
statisticNew.push(stat_obj);
});
console.log(statisticNew)

这是Chris G提供的解决方案,并且工作性能。谢谢!

const statisticNew = Object.entries(datastat.statisticData).map(([key, val]) => ({
[key]: Object.entries(val).map(([name, value]) => ({ name, value }))
}));

>您可以先使用reduce函数减少值,然后相应地mapping值。方法如下:

var datastat = { "statisticData": { "lastStatisticOne": { "min": 0, "max": 10 }, "lastStatisticTwo": { "min": 0, "max": 20 }, "firstStatisticOne": { "min": 0, "max": 30, }, "firstStatisticTwo": { "min": 0, "max": 40, }, }, "statisticValue": []};
reducedValue = Object.entries(datastat.statisticData).reduce((acc, [key, value])=>{
acc[key] = acc[key] || [];
for(const [k, v] of Object.entries(value)){
acc[key].push({name : k, value :v})
}
return acc;
},{});
var result = Object.entries(reducedValue).map(([k,v])=>({[k]:v}));
console.log(result)

最新更新