gpt4 book ai didi

javascript - 如何将对象转换为嵌套对象

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

我是 JavaScript 和编程新手。我通过 AJAX 获取数据。我想重新生成它以获得按部分数据分组的嵌套对象。在这种情况下,我希望它按 yearmonth

分组

这是我的数据和函数:

myObj = [
{"date":'2019-06-05',"name":"abc 0"},
{"date":'2019-06-01',"name":"abc 1"},
{"date":'2019-05-25',"name":"abc 2"},
{"date":'2019-05-15',"name":"abc 3"},
{"date":'2020-06-30',"name":"abc 4"},
{"date":'2020-06-25',"name":"abc 5"},
{"date":'2020-05-28',"name":"abc 6"},
{"date":'2020-05-26',"name":"abc 7"}
];

function regenerate(data) {
var result = {
"allyears": [{}]
};
for (x = 0; x < data.length; x++) {
var year = data[x].date.slice(0, 4);
var month = data[x].date.slice(5, 7);

if (!result.allyears.months) {
result.allyears['year'] = year;
result.allyears.months = [{}];
}
if (!result.allyears.months.data) {
result.allyears.months['month'] = month;
result.allyears.months.data = [{}];
}
result.allyears.months.data[x] = data[x];
}
console.log(result);
return result;
};

regenerate(myObj);

我期望的结果:

{
"allyears": [{
"year": "2019",
"months": [{
"month": "06",
"data": [{
"date": '2019-06-05',
"name": "abc 0"
},
{
"date": '2019-06-01',
"name": "abc 1"
}
]
}, {
"month": "05",
"data": [{
"date": '2019-05-25',
"name": "abc 2"
},
{
"date": '2019-05-15',
"name": "abc 3"
},
]
}]
}]
};

我的函数中缺少什么?

最佳答案

可能不是最聪明的解决方案,但它应该“漂亮地”完成这项工作。该例程利用了 Array.reduce,其中使用了初始累加器(在本例中为空数组),并在循环原始 myObj 数组时检查是否:

  • 年份元素存在于数组中。如果没有,它会创建它。
  • 月份元素存在于年份元素中。如果没有,它会创建它。
  • 创建完所有内容后,它会将数据添加到当前月份。

我将在下面的代码片段中添加一些评论以进一步解释,输出对我来说似乎没问题。

const myObj = [
{"date":'2019-06-05',"name":"abc 0"},
{"date":'2019-06-01',"name":"abc 1"},
{"date":'2019-05-25',"name":"abc 2"},
{"date":'2019-05-15',"name":"abc 3"},
{"date":'2020-06-30',"name":"abc 4"},
{"date":'2020-06-25',"name":"abc 5"},
{"date":'2020-05-28',"name":"abc 6"},
{"date":'2020-05-26',"name":"abc 7"}
];

let res = {
allyears: myObj.reduce((acc, next) => {
let [year, month, day] = next.date.split('-');
// ^-- Acquire year, month and day (actually, day is not needed) from the original date string.
let yearRef = acc.find(i => i.year === year);
// ^-- checks whether the current year already exists in the array.
if (!yearRef) acc.push({year}), yearRef = acc[acc.length - 1];
// ^-- if it doesn't, it creates it and fill the above reference of it.
yearRef.months = yearRef.months || [];
// ^-- same as the year above, but with month.
let monthRef = yearRef.months.find(i => i.month === month);
if (!monthRef) yearRef.months.push({month}), monthRef = yearRef.months[yearRef.months.length - 1]// ^-- same as above, with month.
monthRef.data = (monthRef.data || []).concat(next);
// ^-- once the month element is available, add the next element to data. If data does not yet exist, init it.
return acc;
}, [])
};

console.log(res);

关于javascript - 如何将对象转换为嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56685724/

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