1

I am having problem with using Array.prototype.map() in Javascript

In specific, I am refactoring a JSON file in my react app, which is `

{
        "id": 1,
        "title": "Manage data in Docker",
        "description": "How to use volume and bind mounts in Docker",
        "content": "How to use volume and bind mounts in Docker",
        "author": {
            "username": "vangdo",
            "firstName": "Vang",
            "lastName": "Do",
            "email": "vangdo@gmail.com",
            "birthDate": "2022-11-05",
            "createdAt": null
        },
        "createdAt": "2022-11-05T00:00:00"
    }

The output I want to get is:

{
        "id": 1,
        "title": "Manage data in Docker",
        "description": "How to use volume and bind mounts in Docker",
        "content": "How to use volume and bind mounts in Docker",
        "author": "vangdo",
        "createdAt": "2022-11-05T00:00:00"
    },

I have tried mutiple way like use Array.prototype.map(), however I cannot get the expected result. Can someone help me with this issue? Thank you!

Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
dangerzone
  • 25
  • 4

1 Answers1

1

You only need to destructure your existing JSON and get the properties you want.

Try like this:

const data = [
  {
    id: 1,
    title: "Manage data in Docker",
    description: "How to use volume and bind mounts in Docker",
    content: "How to use volume and bind mounts in Docker",
    author: {
      username: "vangdo",
      firstName: "Vang",
      lastName: "Do",
      email: "vangdo@gmail.com",
      birthDate: "2022-11-05",
      createdAt: null,
    },
    createdAt: "2022-11-05T00:00:00",
  },
];

const output = data.map(
  ({
    id,
    title,
    description,
    content,
    author: { username: author },
    createdAt,
  }) => ({ id, title, description, content, author, createdAt })
);

console.log(output);
Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43