-1

I feel like my problem is really easy to solve, but I cannot see it. I have simple thing to do, get myObject from another function and store this in my storage object. For this task I created storageHandler function. Everything works fine, but Object.assign is not reaching my 'ID' that I declared in this function earlier. This is weird because I don't know how to tell my function that 'ID' is variable, not a string. I just expect it to be {1212313: {...}} but instead it gives me {ID: {...}}.
Someone have any idea how to fix it?

  let  storage = {}

  const myObject =  {       
  ID: '1223424525221',
  name: 'Thomas',
  mail: 'example@example.com'
  }


  storageHandler = data => {
    const {ID} = data;
    
    Object.assign(storage, {ID: data})
    console.log(storage)
  }

  storageHandler(myObject)
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Tsived
  • 13
  • 3
  • If you are setting a single property, why not just `storage[ID] = data`? Seems like you are over complicating this. – Taplar Dec 11 '20 at 19:53
  • @Taplar yea, I just didn`t know about this way, thank you for telling it. – Tsived Dec 11 '20 at 20:00
  • Also a duplicate of https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json – Taplar Dec 11 '20 at 20:05

3 Answers3

1

That's because in javascript this

a = { b: 1 };

is the same as

a = { "b": 1 };

You should change the Object.assign() for something like this

storage[ID] = data;
cape_bsas
  • 638
  • 5
  • 13
0

You are using string as a property name. Use computed property name like [ID] instead of ID. Computed property allows you to have an expression be computed as a property name on an object.

let storage = {};

const myObject = {
  ID: '1223424525221',
  name: 'Thomas',
  mail: 'example@example.com',
};

storageHandler = (data) => {
  const { ID } = data;

  Object.assign(storage, { [ID]: data });
  console.log(storage);
};

storageHandler(myObject);
mr hr
  • 3,162
  • 2
  • 9
  • 19
0

You should use the value of ID as key of object using [].

Object.assign(storage, {[ID]: data})
michael
  • 4,053
  • 2
  • 12
  • 31