Home > Mobile >  Formatting Arrays of Objects into Objects (ES6 Way)
Formatting Arrays of Objects into Objects (ES6 Way)

Time:12-05

I am trying to create a pretty Objects of arrays but this come instead.

{
    "label": [
        "Instagram"
    ],
    "value": [
        "@username"
    ]
}

So, how can I change it? What I want is to be like this

{
    "label": "instagram",
    "value": "@username"
},

I don't know how it happened, but my guess is it was the result of me using formik to define initialValues of a complex nested array from strapi. I was using array.map to map the objects. Hence perhaps thats why it was so messy.

So what is the solution for this? Formatting Arrays of Arrays into Objects? Merging? Converting? I have no idea what it was called. Thanks in advance for anybody replying this.

(updated) The initialValues:

const formik = useFormik({
enableReinitialize: true,
initialValues: {
  name: vendor?.name || '',
  description: vendor?.description || '',
  company: {
    social_media: [
      {
        label: vendor.company?.social_media.map((x) => x.label) || '',
        value: vendor.company?.social_media.map((x) => x.value) || ''
      }
    ]
  }
},

CodePudding user response:

You can use for..in and array join method

const data = {
  "label": [
    "Instagram"
  ],
  "value": [
    "@username"
  ]
};

for (let keys in data) {
  data[keys] = data[keys].join(',')

};

console.log(data)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Array.map returns an array if you don't want any object use Array.foreach

Or

Use [...Array.map()]

    label: [...vendor.company?.social_media.map((x) => x.label)] 
    value: [...vendor.company?.social_media.map((x) => x.value) 
  • Related