Search code examples
javascriptarray-map

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);


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.