Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add special character in array map?

How to add special characters like : to array map ? I want to achieve this.

'10': ["11/21/2022", "11/25/2022"]

this is what I have so far

const data = [{
  "user_id": "10",
  "dates": ["11/21/2022", "11/25/2022"]
}]

const output = data.map(({
  user_id,
  dates
}) => [user_id, dates]);
console.log(output);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’m going to guess that you’re looking for an array like this as your result:

[
    {
        10: ["11/21/2022", "11/25/2022"]
    },
    // ...possibly others here...
]

If so, return a non-array object from your map call rather than an array:

const output = data.map(({ user_id, dates }) => ({[user_id]: dates}));
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^

Example:

const data = [
    {
        user_id: "10",
        dates: ["11/21/2022", "11/25/2022"],
    },
];

const output = data.map(({ user_id, dates }) => ({[user_id]: dates}));
console.log(output);

Note how that uses computed property name syntax to create the property in the object, [user_id]: dates. That creates a property using the value of user_id as the name.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading