[英]How can I store previous values instead of storing the value in array of objects in react state
I am storing the prev values in an array of objects, for example [{ActFollow: 'BlN'},{ActSendGift: 'BlY'},{ActSubscribe: 'BlY'}]
I want to store the key and values in an object like this {ActFollow: 'BlN',ActSendGift: 'BlY', ActSubscribe: 'BlY'}我将 prev 值存储在对象数组中,例如
[{ActFollow: 'BlN'},{ActSendGift: 'BlY'},{ActSubscribe: 'BlY'}]
我想将键和值存储在对象中像这样 {ActFollow: 'BlN',ActSendGift: 'BlY', ActSubscribe: 'BlY'}
const [activityTypes, setActivityTypes] = useState<any>([]); // state
.then((response: any) => {
setActivityTypes((oldArray: any) => [
...oldArray,
{[item.channelSettingTypeId]: response.settingValue},
]);
});
You can reduce the array of objects into an object.您可以将对象数组缩减为一个对象。
You can do it by spreading (...) the current object into the resultant object, as shown below:您可以通过将 (...) 当前对象传播到结果对象中来做到这一点,如下所示:
const arrOfObjs = [{ ActFollow: "BlN" }, { ActSendGift: "BlY" }, { ActSubscribe: "BlY" }], obj = arrOfObjs.reduce((res, o) => ({ ...res, ...o }), {}); console.log(obj);
You can also do it using Object.assign , as shown below:您也可以使用Object.assign来完成,如下所示:
const arrOfObjs = [{ ActFollow: "BlN" }, { ActSendGift: "BlY" }, { ActSubscribe: "BlY" }], obj = arrOfObjs.reduce((res, o) => Object.assign(res, o), {}); console.log(obj);
How about this, if the nesting is only one level deep这个怎么样,如果嵌套只有一层深
const data = [{ActFollow: 'BlN',ActSendGift: 'BlY', ActSubscribe: 'BlY'}] console.log([{...data[0],"hey" : "world"}])
const items = [{ActFollow: 'BlN'},{ActSendGift: 'BlY'},{ActSubscribe: 'BlY'}] let object = {} items.forEach(item=>{ for (const [key, value] of Object.entries(item)) { object = { ...object, [key]: value } } }) console.log(object)
You can use this simple idea in React also.你也可以在 React 中使用这个简单的想法。 Just hold on the default empty object in state and update the object.
只需保持状态中的默认空对象并更新对象即可。
Use Spread Operator使用展开运算符
const items = [{ActFollow: 'BlN', Anurag: 26},{ActSendGift: 'BlY'},{ActSubscribe: 'BlY'}] let obj ={} items.forEach((item) => { obj = { ...obj, ...item } }) console.log(obj)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.