[英]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. opensOrders是我创建的新状态对象。 What is best solution for this?
最好的解决方案是什么? Thanks
谢谢
Your map should look like this. 您的地图应如下所示。 (Note the return statement in map function)
(请注意map函数中的return语句)
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
})
})
To add dynamic keys to a object in javascript we use []. 要将动态键添加到javascript中的对象,我们使用[]。
var x = [{ _id : 1, name: Suzuki}];
x[0]['opened'] = true;
console.log(x);
// [{ _id : 1, name: Suzuki, opened: true}];
Use foreach()
to loop through all the orders in the array and add the desired property for each order. 使用
foreach()
数组中的所有订单,并为每个订单添加所需的属性。
let orders = [{ _id: 1, name: 'honda', }, { _id: 2, name: 'suzuki', }, { _id: 3, name: 'audi', }] orders.forEach(o => o.opened = true) console.log(orders)
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; }
Assuming response
contains the first array in your OP: 假设
response
包含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. response.map(order => ({ ...order, open: true})
向数组中的每个order
添加一个值为true
的键open
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.