javascriptreactjsspread-syntax

Spread for an object in React


I have an array of objects and I want it to become an object that would go { 44: "autoTest", 94: "autoTest", ...}

[
  0: {
    id: 1, 
    name: "test", 
    description: "a description"
  }, 
  1: {
    id: 2, 
    name: "test 2", 
    description: "a description french baguette"
  }
]

would become

{
  1: "test", 
  2: "test2"
}

My code so far with some console.log() :

const { options } = this.state;
console.log(options); // […] 0: Object { id: 44, name: "autoTest", description: "test uniUpdate", … } 1: Object { id: 94, name: "autoTest", description: "test uni", … }
​let obj2 = {};
if (options.length > 0) {
  options.map((item, key) => {
    const id = item.id;
    const name = item.name;
    let obj1 = { [id]: name };
    console.log(obj1); // Object { 44: "autoTest" } for example
    obj2 = { ...obj1 };
  });
  console.log(obj2); // Object { 16: "Test 3" } is called like two times and is obviously not what I expected
}

Some hints ?


Solution

  • This does not need to be so complex. You can simplify it by using reduce():

    const data = [
      {
        id: 1, 
        name: "test", 
        description: "a description"
      }, 
      {
        id: 2, 
        name: "test 2", 
        description: "a description french baguette"
      }
    ]
    
    const result = data.reduce((a, { id, name }) => ({ ...a, [id]: name }), {});
    console.log(result);