0

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},
            ]);
          });
4
  • You want to store each object from array of objects in single object ? Commented Jun 12, 2022 at 7:08
  • yes, you are right Commented Jun 12, 2022 at 7:09
  • 1
    kindly check this link, I think it is helpful for you Commented Jun 12, 2022 at 7:17
  • @Jerin Just added answer. Please check that. Its pretty simple Commented Jun 12, 2022 at 7:18

4 Answers 4

1

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"}])

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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);

Comments

0

Use Spread Operator

const items = [{ActFollow: 'BlN', Anurag: 26},{ActSendGift: 'BlY'},{ActSubscribe: 'BlY'}]
    let obj ={}
    items.forEach((item) => {
      obj = {
        ...obj,
        ...item
        }
      })
    console.log(obj)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.