다음과 같은 배열의 배열이 있다고 가정합니다 -
const arr = [ [ ['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk'], [ ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager'] ] ] ];
그러한 배열을 취하는 JavaScript 함수를 작성해야 합니다. 함수는 이 배열 배열을 기반으로 개체 배열을 생성해야 합니다.
출력 배열에는 각 고유 사용자에 대한 개체와 이에 대한 기타 세부 정보가 포함되어야 합니다.
따라서 배열의 출력은 다음과 같아야 합니다. -
const output = [
{firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk'},
{firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'}
]; 예시
이에 대한 코드는 -
const arr = [
[
['firstName', 'Joe'],
['lastName', 'Blow'],
['age', 42],
['role', 'clerk'],
[
['firstName', 'Mary'],
['lastName', 'Jenkins'],
['age', 36],
['role', 'manager']
]
]
];
const convertToObject = (arr = []) => {
const empty = {};
const res = arr.map(el => {
const object = this;
el.forEach(attr => {
let name = attr[0], value = attr[1];
object[name] = value;
return object;
}, object);
return this;
}, empty);
return res;
}
console.log(convertToObject(arr)); 출력
콘솔의 출력은 -
[
{
firstName: 'Joe',
lastName: 'Blow',
age: 42,
role: 'clerk',
'firstName,Mary': [ 'lastName', 'Jenkins' ]
}
]