2

Object 1:

{positive: ['happy', 'excited', 'joyful'], negative: ['depressed', 'sad', 'unhappy']}

Object 2:

{happy: 6, excited: 1, unhappy: 3}

What I want - Result:

{positive: 7, negative: 3}

How do I achieve this?

I have used the following to get the category object 2 falls into but I'm not sure how to dynamically create the third object as the size of these objects grow. I cannot use for...of or for...in due to eslint airbnb rules

    function getKeyByValue(value) {
        return Object.keys(object).find((key) => object[key] === value);
    }
zosozo
  • 393
  • 2
  • 5
  • 16

2 Answers2

2

This can be done using Array#reduce over Object.entries to create the new object. For each entry, destructured as [key, feelings], we calculate the sum using a nested reduce: for each feeling in feelings, we use the value from object2, if exists, or 0 otherwise using short circuit evaluation (object2[feeling] || 0), like so:

let result = Object.entries(object1).reduce((result, [key, feelings]) => {
  result[key] = feelings.reduce((sum, feeling) => sum + (object2[feeling] || 0), 0);
  return result;
}, {});

Demo:

let object1 = { positive: ["happy", "excited", "joyful"], negative: ["depressed", "sad", "unhappy"] };
let object2 = { happy: 6, excited: 1, unhappy: 3 };


let result = Object.entries(object1).reduce((result, [key, feelings]) => {
  result[key] = feelings.reduce((sum, feeling) => sum + (object2[feeling] || 0), 0);
  return result;
}, {});

console.log(result);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
0

For example, you can use reduce:

    obj1 = {positive: ['happy', 'excited', 'joyful'], negative: ['depressed', 'sad', 'unhappy']}
    obj2 = {happy: 6, excited: 1, unhappy: 3}
    
    const result ={}
    
    for (let key of Object.keys(obj1)) {
        result[key] = obj1[key].reduce(
            (acc, value) => { return acc + (obj2[value] || 0) }, 0)
    }
    
    console.log(result)

Notes:

  1. for ... of Object.keys() is more preferable in most situations than for ... in because for ... in iterate not only over the object's own keys, but also over its prototype chains.
  2. Instead Object.keys() you can also use Reflect.ownKeys()
  • I have tried something like this but airbnb eslint is complaining due to for of/for in loops so I'm trying to figure out different approaches – zosozo Oct 24 '20 at 19:00