ภาพรวม
สมมติว่าเรามีอาร์เรย์ของอ็อบเจ็กต์ดังนี้:
const arr = [
{ col1: ["a", "b"], col2: ["c", "d"] },
{ col1: ["e", "f"], col2: ["g", "h"] }
];
เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ดังกล่าวและคืนค่าอาร์เรย์ใหม่ที่ค่าของแต่ละคีย์ (ซึ่งเดิมเป็นอาร์เรย์) กลายเป็นค่าเดี่ยว คือ อิลิเมนต์ที่สอง (ดัชนี 1) ของอาร์เรย์เดิม
ผลลัพธ์ที่คาดหวัง
const output = [
{ col1: "b", col2: "d" },
{ col1: "f", col2: "h" }
];
ตัวอย่างโค้ด
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' } ]