[英]Javascript iterate through nested Object and return transformed and renamed Array of objects
我已經檢查了有關嵌套對象的所有可用答案,但到目前為止沒有任何幫助。 我確實有一個深層嵌套的 object ,例如:
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);
}
}
如何實現正確的 output?
這應該這樣做:
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;
}, []);
這是 Chris G 提供的解決方案,效果很好。 謝謝!
const statisticNew = Object.entries(datastat.statisticData).map(([key, val]) => ({
[key]: Object.entries(val).map(([name, value]) => ({ name, value }))
}));
您可以遍歷 dataStat 的鍵並獲得預期的 output ,如下所示:
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)
您可以首先使用reduce
function 減少值,然后相應地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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.