Home > Software engineering >  Write variable in text format in array
Write variable in text format in array

Time:10-27

I have problem in writting variable as key in array

setOrderedItems((cartItem) => ({...cartItem, item.id: item.name}));

I've tried {item.id}, ${item.id} but nothing helps.

const [orderedItems, setOrderedItems] = useState([]);
const handleOnChange = (item, eventStatus) => {
if(eventStatus){
  setOrderedItems((cartItem) => ({...cartItem, [item.id]: item.name}));
}
}

The item is single item which has structe

first item {id: 1, name: 'test1'} 
second item {id: 1, name: 'test2'} 
third item {id: 2, name: 'test3}

What I want to achive is {1: ['test1', 'test2'], 2: 'test3'}

CodePudding user response:

The problem is that you illegally added the id attribute to the key.

setOrderedItems((cartItem) => ({...cartItem, item:[{ id: item.name}]}));

CodePudding user response:

If item.id holds the key to be used for the item.name value in the object you're creating, use square brackets:

setOrderedItems((cartItem) => ({ ...cartItem, [item.id]: item.name }))

Update: so apparently you want to accumulate multiple string values under the same key. In more detail, from these items:

[
  { id: 1, name: 'test1' },
  { id: 1, name: 'test2' },
  { id: 2, name: 'test3' }
]

you want to obtain

{
  1: ['test1', 'test2'],
  2: ['test3']
}

This should do it:

const [orderedItems, setOrderedItems] = React.useState({})

const data = [
  { id: 1, name: 'test1' },
  { id: 1, name: 'test2' },
  { id: 2, name: 'test3' }
]
const addItem = React.useCallback(({id, name}) => {
  setOrderedItems({
    ...orderedItems,
    [id]: [...(orderedItems[id] || []), name ])
  })
}, [])
data.forEach(addItem)
console.log(orderedItems)
/* 
 {
   1: ['test1', 'test2'],
   2: ['test3']
 }
*/
  • Related