สมมติเรามีออบเจกต์สองตัวดังนี้:
const obj1 = {
positive: ['happy', 'excited', 'joyful'],
negative: ['depressed', 'sad', 'unhappy']
};
const obj2 = {
happy: 6,
excited: 1,
unhappy: 3
};
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับออบเจกต์ทั้งสองเข้ามา ฟังก์ชันควรใช้ทั้งสองออบเจกต์เพื่อคำนวณคะแนน positive และ negative แล้วคืนออบเจกต์แบบนี้:
const output = {positive: 7, negative: 3};
ตัวอย่างโค้ด
const obj1 = {
positive: ['happy', 'excited', 'joyful'],
negative: ['depressed', 'sad', 'unhappy']
};
const obj2 = {
happy: 6,
excited: 1,
unhappy: 3
};
const findPositiveNegative = (obj1 = {}, obj2 = {}) => {
const result = {};
for (let key of Object.keys(obj1)) {
result[key] = obj1[key].reduce((acc, value) => {
return acc + (obj2[value] || 0);
}, 0)
};
return result;
};
console.log(findPositiveNegative(obj1, obj2));
ผลลัพธ์
ผลลัพธ์ที่แสดงในคอนโซลจะเป็นดังนี้:
{ positive: 7, negative: 3 }