다음과 같은 객체 배열이 있다고 가정해 보겠습니다. -
const arr = [
{ 'name': 'JON', 'flight':100, 'value': 12, type: 'uns' },
{ 'name': 'JON', 'flight':100, 'value': 35, type: 'sch' },
{ 'name': 'BILL', 'flight':200, 'value': 33, type: 'uns' },
{ 'name': 'BILL', 'flight':200, 'value': 45, type: 'sch' }
]; 우리는 그러한 객체 배열 중 하나를 취하는 JavaScript 함수를 작성해야 합니다. 함수는 객체에서 '값' 및 '유형' 키를 제거하고 해당 값을 각각의 객체에 키 값 쌍으로 추가해야 합니다.
따라서 위의 입력에 대한 출력은 다음과 같아야 합니다. -
const output = [
{ 'name': 'JON', 'flight':100, 'uns': 12, 'sch': 35 },
{ 'name': 'BILL', 'flight':200, 'uns': 33, 'sch': 45}
]; 출력
이에 대한 코드는 -
const arr = [
{ 'name': 'JON', 'flight':100, 'value': 12, type: 'uns' },
{ 'name': 'JON', 'flight':100, 'value': 35, type: 'sch' },
{ 'name': 'BILL', 'flight':200, 'value': 33, type: 'uns' },
{ 'name': 'BILL', 'flight':200, 'value': 45, type: 'sch' }
];
const groupArray = (arr = []) => {
const res = arr.reduce(function (hash) {
return function (r, o) {
if (!hash[o.name]) {
hash[o.name] = { name: o.name, flight: o.flight };
r.push(hash[o.name]);
}
hash[o.name][o.type] = (hash[o.name][o.type] || 0) + o.value;
return r;
}
}(Object.create(null)), []);
return res;
};
console.log(groupArray(arr)); 출력
콘솔의 출력은 -
[
{ name: 'JON', flight: 100, uns: 12, sch: 35 },
{ name: 'BILL', flight: 200, uns: 33, sch: 45 }
]