1

For a react project I need 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 ?

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"
    }
  },
  ...
]
6
  • 2
    if you know how to do the map go for it. this is a good use case of map Commented Feb 11, 2022 at 14:04
  • Particular prop-names such as acf and rendered need to be removed - in order to achieve the target structure, is that correct? Commented Feb 11, 2022 at 14:06
  • I'm a newby... don't know how to map this array to destructure sub objects... ;) Commented Feb 11, 2022 at 14:06
  • yes @jsN00b it's what i want to do ! Commented Feb 11, 2022 at 14:07
  • Please try this: const newArr = origArr.map(obj => ({ id: obj.id, title: obj.title.rendered, ...obj.acf})); Or, you may use kiranvj's solution below. It uses destructuring the iterator. Commented Feb 11, 2022 at 14:08

1 Answer 1

3

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

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

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.