Home > Enterprise >  Problem with refactoring JSON file in ReactJS application
Problem with refactoring JSON file in ReactJS application

Time:11-07

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": "[email protected]",
            "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!

CodePudding user response:

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: "[email protected]",
      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);

  • Related