다음과 같은 두 개의 개체가 있다고 가정합니다.
const obj1 = {
positive: ['happy', 'excited', 'joyful'],
negative: ['depressed', 'sad', 'unhappy']
};
const obj2 = {
happy: 6,
excited: 1,
unhappy: 3
}; 우리는 두 개의 그러한 객체를 취하는 JavaScript 함수를 작성해야 합니다. 그런 다음 함수는 이 두 객체를 모두 사용하여 양수 및 음수 점수를 계산하고 다음과 같은 객체를 반환해야 합니다. -
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 }