다음과 같은 사람에 대한 데이터를 포함하는 개체가 있다고 가정해 보겠습니다.
const obj = {
"Person1_Age": 22,
"Person1_Height": 170,
"Person1_Weight": 72,
"Person2_Age": 27,
"Person2_Height": 160,
"Person2_Weight": 56
}; 우리는 하나의 그러한 객체를 취하는 JavaScript 함수를 작성해야 합니다. 그리고 우리의 기능은 고유한 각 개인에 관한 데이터를 고유한 개체로 분리해야 합니다.
따라서 위의 개체에 대한 출력은 다음과 같아야 합니다. -
const output = [
{
"name": "Person1",
"age": "22",
"height": 170,
"weight": 72
},
{
"name": "Person2",
"age": "27",
"height": 160,
"weight": 56
}
]; 예시
이에 대한 코드는 -
const obj = {
"Person1_Age": 22,
"Person1_Height": 170,
"Person1_Weight": 72,
"Person2_Age": 27,
"Person2_Height": 160,
"Person2_Weight": 56
};
const separateOut = (obj = {}) => {
const res = [];
Object.keys(obj).forEach(el => {
const part = el.split('_');
const person = part[0];
const info = part[1].toLowerCase();
if(!this[person]){
this[person] = {
"name": person
};
res.push(this[person]);
}
this[person][info] = obj[el];
}, {});
return res;
};
console.log(separateOut(obj)); 출력
콘솔의 출력은 -
[
{ name: 'Person1', age: 22, height: 170, weight: 72 },
{ name: 'Person2', age: 27, height: 160, weight: 56 }
]