简体   繁体   中英

Convert array inside JSON into object in javascript

I have the following data which is coming from a GraphQL endpoint :

{
  "data": {
    "metatags": [
      {
        "title": "Metatag title",
        "description": "Metatag description"
      }
    ],
    "herounits": [
      {
        "title": "Hero unit title",
        "description": "Hero unit description"
      }
    ]
  }
}

I need to replace the arrays inside of it into JSON objects as the following:

{
  "data": {
    "metatags": {
      {
        "title": "Metatag title",
        "description": "Metatag description"
      }
    },
    "herounits": {
      {
        "title": "Hero unit title",
        "description": "Hero unit description"
      }
    }
  }
}

Been trying different approaches but none been working yet.

Your desire object is not valid, you have an extra level of object nesting without property names.

Assuming what you actually want is:

{
  "data": {
    "metatags": {
        "title": "Metatag title",
        "description": "Metatag description"
    },
    "herounits": {
        "title": "Hero unit title",
        "description": "Hero unit description"
    }
  }
}

you can do it by replacing each property with the value in element 0 of the array.

 let obj = { "data": { "metatags": [ { "title": "Metatag title", "description": "Metatag description" } ], "herounits": [ { "title": "Hero unit title", "description": "Hero unit description" } ] } }; Object.keys(obj.data).forEach(k => obj.data[k] = obj.data[k][0]); 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM