다음과 같은 일부 사용자에 대한 데이터가 있다고 가정합니다. -
const obj = {
"Mary": {
"2016-1": 2,
"2016-5": 1,
"2016-3": 1
},
"Paul": {
"2016-1": 1,
"2016-3": 1
},
"moth": {
"2016-1": 2,
"2016-5": 1
}
}; 우리는 하나의 그러한 객체를 취하는 JavaScript 함수를 작성해야 합니다. 우리 함수는 이 사용자 데이터를 개체로 그룹화해야 하며 각 고유 날짜는 개체로 표시됩니다.
예시
이에 대한 코드는 -
const obj = {
"Mary": {
"2016-1": 2,
"2016-5": 1,
"2016-3": 1
},
"Paul": {
"2016-1": 1,
"2016-3": 1
},
"moth": {
"2016-1": 2,
"2016-5": 1
}
};
const groupByDate = (obj = {}) => {
const names = Object.keys(obj);
const res = {};
for(let i = 0; i < names.length; i++){
const name = names[i];
const dates = Object.keys(obj[name]);
for(let j = 0; j < dates.length; j++){
const date = dates[j];
if(!res.hasOwnProperty(date)){
res[date] = {
names: [name],
values: [obj[name][date]]
}
}
else{
res[date].names.push(name);
res[date].values.push(obj[name][date]);
};
};
};
return res;
};
console.log(groupByDate(obj)); 출력
콘솔의 출력은 -
{
'2016-1': { names: [ 'Mary', 'Paul', 'moth' ], values: [ 2, 1, 2 ] },
'2016-5': { names: [ 'Mary', 'moth' ], values: [ 1, 1 ] },
'2016-3': { names: [ 'Mary', 'Paul' ], values: [ 1, 1 ] }
}