Saban
Saban

Reputation: 387

React How to add new dynamic key to existing state?

I have getting the data from database as an array. So now I'm getting array like this:

orders:[
{
_id:1,
name: honda,
}
{
_id:2,
name: suzuki,
}
{
_id:3,
name: audi,
}
]

So my question is how can I attach new key value to the array, so It needs to look like this:

orders:[
{
_id:1,
name: honda,
opened:true,
}
{
_id:2,
name: suzuki,
opened:true,
}
{
_id:3,
name: audi,
opened:true,
}
]

For now I'm trying with this code, but this doesn't work:

getOrders(orders).then(response => {
        response.map(itm=>{
            const ordersData=[...itm]
            const opened={opened:true}
            this.setState({
                openedOrders: [ordersData,opened]
            })
        })
}) 

openedOrders is new state object that I create. What is best solution for this? Thanks

Upvotes: 0

Views: 1916

Answers (5)

G_S
G_S

Reputation: 7110

Your map should look like this. (Note the return statement in map function)

orders.map(item=> {
  return {...item, opened:true}  

})

So your function could look like

getOrders(orders).then(response => {
   let openedOrders =  orders.map(item=> {
       return {...item, opened:true}  
     })
   this.setState({
     openedOrders
   })

}) 

Upvotes: 2

laruiss
laruiss

Reputation: 3816

Assuming response contains the first array in your OP:

getOrders(orders).then(response => {
  const openedOrders = response.map(order => ({ ...order, open: true}))
  this.setState({ openedOrders } )
})

response.map(order => ({ ...order, open: true}) adds a key open with the value true to every order in the array.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386540

You could add a new property to the objects.

var orders = [{ _id: 1, name: 'honda' }, { _id: 2, name: 'suzuki' }, { _id: 3, name: 'audi' }],
    additionalProp = { opened: true };

orders.forEach(o => Object.assign(o, additionalProp));

console.log(orders);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Or map a new array without mutating the original objects.

var orders = [{ _id: 1, name: 'honda' }, { _id: 2, name: 'suzuki' }, { _id: 3, name: 'audi' }],
    additionalProp = { opened: true },
    result = orders.map(o => Object.assign({}, o, additionalProp));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 0

holydragon
holydragon

Reputation: 6728

Use foreach() to loop through all the orders in the array and add the desired property for each order.

let orders = [{
  _id: 1,
  name: 'honda',
}, {
  _id: 2,
  name: 'suzuki',
}, {
  _id: 3,
  name: 'audi',
}]
orders.forEach(o => o.opened = true)
console.log(orders)

Upvotes: 0

Rehan
Rehan

Reputation: 105

To add dynamic keys to a object in javascript we use [].

var x = [{ _id : 1, name: Suzuki}];

x[0]['opened'] =  true;

console.log(x);

// [{ _id : 1, name: Suzuki, opened: true}];

Upvotes: 0

Related Questions