-1

When I need to pass data from other people's API to the frontend, sometimes I need to change some field names. For example, Here's the data I received:

const backend = [
  {
    id: 1,
    posts: [
      {
        id: 1,
        title: 'hello'
      }
    ],
  },
  {
    id: 2,
    posts: [
      {
        id: 3,
        title: 'world'
      }
    ]
  }
]

How to change all field names id into values. Should I refer to use some recursive deep clone functions and modify the key of field accordingly?

Xiangyi Li
  • 85
  • 6
  • [Many, many more duplicates](https://www.google.com/search?q=javascript+change+nested+key+name+object+site:stackoverflow.com) – mplungjan Apr 27 '22 at 12:10

1 Answers1

1

Do like this

const backend = [
  {
    id: 1,
    posts: [
      {
        id: 1,
        title: 'hello'
      }
    ],
  },
  {
    id: 2,
    posts: [
      {
        id: 3,
        title: 'world'
      }
    ]
  }
]
const newbackend = backend.map(({
  id: values,
  ...rest
}) => ({
  values,
  ...rest
}));

console.log(newbackend)