1

I have this array and I want to create new object with the keys and values.

const arr = [
  {
    name: 'ab',
    key: '584577',
  },
  {
    name: 'cd',
    key: '344926',
  },
  {
    name: 'ef',
    key: '804816',
  },
];


for(const item of arr) {
  setNewObject({...newObject, [item.name]: item.key})
}

But results prints nothing. This is my expected result:

   {
      ab: 584577,
      cd: 344926,
      ef: 804816
    }

Here's a LIVE DEMO Can anyone point me in the right direction? Thanks in advance!

Devmix
  • 1,599
  • 5
  • 36
  • 73
  • 2
    set state is asynchronous https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately – cmgchess Apr 12 '23 at 18:20
  • @cmgchess my main issue is that I believe I'm not doing setNewObject({...newObject, [item.name]: item.key}) correctly – Devmix Apr 12 '23 at 18:23
  • `setNewObject(prev => ({...prev, [item.name]: item.key}))` – cmgchess Apr 12 '23 at 18:30
  • `console.log(newObject)` won't show the changes - newObject will only be updated when you re-render, and your useEffect does not trigger on re-render. If you put the output of newObject into your html output you would see the properties once it re-renders. – James Apr 12 '23 at 18:41
  • Does this answer your question? [How do I convert array of Objects into one Object in JavaScript?](https://stackoverflow.com/questions/19874555/how-do-i-convert-array-of-objects-into-one-object-in-javascript) – pilchard Apr 12 '23 at 20:35
  • or [Convert array of objects into a single object](https://stackoverflow.com/questions/72388019/convert-array-of-objects-into-a-single-object) – pilchard Apr 12 '23 at 20:35

1 Answers1

1

Edit: so that it works with for loop as requested

Create a new object and then inside your loop, you assign a new key with its value like this newObj[item.name] = item.key

const arr = [
  {
    name: 'ab',
    key: '584577',
  },
  {
    name: 'cd',
    key: '344926',
  },
  {
    name: 'ef',
    key: '804816',
  },
];

let newObj = {}
for(const item of arr) {
    newObj[item.name] = item.key
}

console.log(newObj);
Chris G
  • 1,598
  • 1
  • 6
  • 18