如何将数组中的对象放在另一个数组中属性?
How grupped array of objects on the property in another array?
我有一个json数据。如何按日期对对象进行分组,以便日期作为一个新对象,并且具有相同日期的数据记录在人员中。以下是源代码和所需视图
也许有人会举个例子,然后我自己完成。
这是我的来源json
[
{
"Info": [
{
"age": "26"
}
],
"Date": "2020-08-14"
},
{
"Info": [
{
"age": "23"
}
],
"Date": "2020-08-14"
},
{
"Info": [
{
"age": "30"
}
],
"Date": "2020-08-15"
}
]
这是我想要的 json
[
{
"name": "2020-08-14",
"persons": [
{
"Info": [
{
"age": "26"
}
],
"Date": "2020-08-14"
},
{
"Info": [
{
"age": "23"
}
],
"Date": "2020-08-14"
}]
},
{
"name": "2020-08-15",
"persons": [
{
"Info": [
{
"age": "30"
}
],
"Date": "2020-08-15"
}
]
}
]
提前致谢
用Array#reduce累积result-data。遍历对象并查看在累积的结果对象中是否存在具有此日期的 属性。如果没有创建它并在其中添加一个新对象,其中包含 name-date 和带有空数组的 person-property。在此之后,在两种情况下都将孔对象添加到人数组中。
最后获取 Object#values 以从 result-object.
中获取所需的数组
let arr = [
{
"Info": [
{
"age": "26"
}
],
"Date": "2020-08-14"
},
{
"Info": [
{
"age": "23"
}
],
"Date": "2020-08-14"
},
{
"Info": [
{
"age": "30"
}
],
"Date": "2020-08-15"
}
];
let res = Object.values(arr.reduce((acc, cur) => {
if (acc[cur.Date]=== undefined) {
acc[cur.Date] = {name: cur.Date, persons: []};
}
acc[cur.Date].persons.push(cur);
return acc;
},{}));
console.log(res);
我有一个json数据。如何按日期对对象进行分组,以便日期作为一个新对象,并且具有相同日期的数据记录在人员中。以下是源代码和所需视图 也许有人会举个例子,然后我自己完成。
这是我的来源json
[
{
"Info": [
{
"age": "26"
}
],
"Date": "2020-08-14"
},
{
"Info": [
{
"age": "23"
}
],
"Date": "2020-08-14"
},
{
"Info": [
{
"age": "30"
}
],
"Date": "2020-08-15"
}
]
这是我想要的 json
[
{
"name": "2020-08-14",
"persons": [
{
"Info": [
{
"age": "26"
}
],
"Date": "2020-08-14"
},
{
"Info": [
{
"age": "23"
}
],
"Date": "2020-08-14"
}]
},
{
"name": "2020-08-15",
"persons": [
{
"Info": [
{
"age": "30"
}
],
"Date": "2020-08-15"
}
]
}
]
提前致谢
用Array#reduce累积result-data。遍历对象并查看在累积的结果对象中是否存在具有此日期的 属性。如果没有创建它并在其中添加一个新对象,其中包含 name-date 和带有空数组的 person-property。在此之后,在两种情况下都将孔对象添加到人数组中。
最后获取 Object#values 以从 result-object.
let arr = [
{
"Info": [
{
"age": "26"
}
],
"Date": "2020-08-14"
},
{
"Info": [
{
"age": "23"
}
],
"Date": "2020-08-14"
},
{
"Info": [
{
"age": "30"
}
],
"Date": "2020-08-15"
}
];
let res = Object.values(arr.reduce((acc, cur) => {
if (acc[cur.Date]=== undefined) {
acc[cur.Date] = {name: cur.Date, persons: []};
}
acc[cur.Date].persons.push(cur);
return acc;
},{}));
console.log(res);