다음과 같은 배열의 배열이 있다고 가정합니다 -
const arr = [ [ ['juice', 'apple'], ['maker', 'motts'], ['price', 12] ], [ ['juice', 'orange'], ['maker', 'sunkist'], ['price', 11] ] ];
우리는 그러한 배열 하나를 취하고 입력 배열을 기반으로 구축된 객체의 새로운 배열을 반환하는 JavaScript 함수를 작성해야 합니다.
따라서 위의 배열의 경우 출력은 다음과 같아야 합니다. -
const output = [
{juice: 'apple', maker: 'motts', price: 12},
{juice: 'orange', maker: 'sunkist', price: 11}
]; 예시
이에 대한 코드는 -
const arr = [
[
['juice', 'apple'], ['maker', 'motts'], ['price', 12]
],
[
['juice', 'orange'], ['maker', 'sunkist'], ['price', 11]
]
];
const arrayToObject = arr => {
let res = [];
res = arr.map(list => {
return list.reduce((acc, val) => {
acc[val[0]] = val[1];
return acc;
}, {});
});
return res;
};
console.log(arrayToObject(arr)); 출력
콘솔의 출력 -
[
{ juice: 'apple', maker: 'motts', price: 12 },
{ juice: 'orange', maker: 'sunkist', price: 11 }
][
{ juice: 'apple', maker: 'motts', price: 12 },
{ juice: 'orange', maker: 'sunkist', price: 11 }
]