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": "[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!

0

1 Answer 1

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: "[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);

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

2 Comments

Or just ({ author: { username: author }, ...rest }) => ({ ...rest, author })
Or without destructuring map(item => ({ ...item, author: item?.author?.username }))

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.