다음과 같은 객체 배열이 있다고 가정해 보겠습니다. -
const arr = [{
name : 'Client 1',
total: 900,
value: 12000
}, {
name : 'Client 2',
total: 10,
value: 800
}, {
name : 'Client 3',
total: 5,
value : 0
}]; 이러한 배열 하나를 취하고 각 객체 속성에 대해 별도의 배열을 추출하는 JavaScript 함수를 작성해야 합니다.
따라서 각 개체의 이름 속성에 대해 하나의 배열, 즉 합계에 대해 하나, 값에 대해 하나입니다. 더 많은 속성이 있었다면 더 많은 배열을 분리했을 것입니다.
예시
이에 대한 코드는 -
const arr = [{
name : 'Client 1',
total: 900,
value: 12000
}, {
name : 'Client 2',
total: 10,
value: 800
}, {
name : 'Client 3',
total: 5,
value : 0
}];
const separateOut = arr => {
if(!arr.length){
return [];
};
const res = {};
const keys = Object.keys(arr[0]);
keys.forEach(key => {
arr.forEach(el => {
if(res.hasOwnProperty(key)){
res[key].push(el[key])
}else{
res[key] = [el[key]];
};
});
});
return res;
};
console.log(separateOut(arr)); 출력
콘솔의 출력은 -
{
name: [ 'Client 1', 'Client 2', 'Client 3' ],
total: [ 900, 10, 5 ],
value: [ 12000, 800, 0 ]
}