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'}
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:
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. 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.