1

I am trying to achieve the following: Say i have an object like this:

myObj = {
   john: {1: ['a', 'b',..], 2: ['aa', 'vv',...],
   tom: {1: ['ab', 'bb',..], 2: ['aa', 'vv',...],
}

To achieve the above i am doing something like this which works

    function (name, myNum, myList) {
        let myObj = Object.assign({}, state);
        // name and myNum and myList values are passed in for this eg i am 
       // hardcoding
       let name = 'jon';
       let myNum = 1;
       let mylist = [1,2,3];
       // I want to replace the if / else with a more elegant solution
       if (myObj.hasOwnProperty(name)) {
         myObj[name][myNum] = myList;
       } else {
         myObj[name] = {[myNum]: myList};
       }
       return myObj;
      }

I am sure there is a much cleaner way to do this, using Object.assign or object spread.

Please advice what would be better approach.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Jonn Ham
  • 27
  • 1
  • 6
  • 1
    Can you tell us what you're trying to do or what the desired output is? – Andrew Li May 11 '18 at 01:36
  • What i want is to create an object like the one mentioned above. So myObj is a object whose values also are objects. I start with an empty object and as objects come in i want to maintain their map. What is want is already achieved by that if statement.. But i dont like that way and instead want to see if i can do the same more elegantly. – Jonn Ham May 11 '18 at 02:49
  • [`...` is not an operator!](https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508) – Felix Kling May 11 '18 at 03:28

1 Answers1

0

Maybe you are looking for

myObj[name] = Object.assign(myObj[name] || {}, {[myNum]: myList});

You can also do

myObj[name] = {...myObj[name], [myNum]: myList};

but this will always create a new object.

You can also combine everything into a single expression:

function (name, myNum, myList) {
  return {
    ...state,
    [name]: {
      ...state[name],
      [myNum]: myList,
     },
  };
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143