다음과 같은 객체 배열이 있다고 가정해 보겠습니다. -
const arr = [
{
col1: ["a", "b"],
col2: ["c", "d"]
},
{
col1: ["e", "f"],
col2: ["g", "h"]
}
]; 우리는 그러한 배열 중 하나를 취하고 다음 출력을 반환하는 JavaScript 함수를 작성해야 합니다.
const output = [
{
col1: "b",
col2: "d"
},
{
col1: "f",
col2: "h"
}
]; 기본적으로 우리는 초기에 배열인 Object keys Value를 단일 값으로 변환하고 그 값이 Object keys 배열의 두 번째 요소가 되기를 원합니다.
이에 대한 코드는 -
const arr = [
{
col1: ["a", "b"],
col2: ["c", "d"]
},
{
col1: ["e", "f"],
col2: ["g", "h"]
}
];
const reduceArray = (arr = []) => {
const res = arr.reduce((s,a) => {
const obj = {};
Object.keys(a).map(function(c) {
obj[c] = a[c][1];
});
s.push(obj);
return s;
}, []);
return res;
};
console.log(reduceArray(arr)); 콘솔의 출력은 -
[ { col1: 'b', col2: 'd' }, { col1: 'f', col2: 'h' } ]