Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS array of objects destructuring?

For a react project i nedd to simplify an array of objects.

I’ve an array of objects coming from wp rest api axios request. Inside objects there are objects. I would like to "remove" this nested object in order to have this :

   [
      {
        "id": 101,
        "title": "CTC20180018",
        "fielda": "valuea",
        "fieldb": "valueb",
        "fieldc": "valuec"
      },
      {
        "id": 102,
        "title": "D2021063365",
        "fielda": "valuea",
        "fieldb": "valueb",
        "fieldc": "valuec"
      },
      ...
    ]

What is the best solution? .map() the array and use destructuring ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The original array :

[
  {
    "id": 101,
    "title": {
      "rendered": "CTC20180018"
    },
    "acf": {
      "fielda": "valuea",
      "fieldb": "valueb",
      "fieldc": "valuec"
    }
  },
  {
    "id": 102,
    "title": {
      "rendered": "D2021063365"
    },
    "acf": {
      "fielda": "valuea",
      "fieldb": "valueb",
      "fieldc": "valuec"
    }
  },
  ...
]

>Solution :

Try something like below using map, Object destructuring and spread operator

const data = [{
    "id": 101,
    "title": {
      "rendered": "CTC20180018"
    },
    "acf": {
      "fielda": "valuea",
      "fieldb": "valueb",
      "fieldc": "valuec"
    }
  },
  {
    "id": 102,
    "title": {
      "rendered": "D2021063365"
    },
    "acf": {
      "fielda": "valuea",
      "fieldb": "valueb",
      "fieldc": "valuec"
    }
  }
]

const result = data.map(({
  id,
  title,
  acf
}) => ({
  id: id,
  title: title.rendered,
  ...acf
}));

console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading