Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tạo đối tượng thứ ba từ hai đối tượng dùng giá trị key trong JavaScript

Giả sử có hai đối tượng:

const obj1 = { 
  positive: ['happy', 'excited', 'joyful'], 
  negative: ['depressed', 'sad', 'unhappy'] 
}; 
const obj2 = { 
  happy: 6, 
  excited: 1, 
  unhappy: 3 
};

Viết hàm nhận vào hai đối tượng này, tính điểm positive và negative dựa trên obj2, trả về đối tượng kết quả.

Kết quả mong đợi:

const output = {positive: 7, negative: 3};

Ví dụ

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));

Kết quả

Kết quả in ra console:

{ positive: 7, negative: 3 }