0

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);
  • `'10': ["11/21/2022", "11/25/2022"]` isn’t a value. Get familiar with [how to access and process objects, arrays, or JSON](/q/11922383/4642212), how to [access properties](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_Accessors), and how to create [objects](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer) or [arrays](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/Array#array_literal_notation). – Sebastian Simon Nov 12 '22 at 10:27
  • 1
    Do you mean you want to create an object like `{"10": ["11/21/2022", "11/25/2022"]}`? (The quotes around the `10` there are optional, but I thought it was clearer to write them in this case.) If so, you can't do that with `map`, `map` produces an **array**. Or did you perhaps want an array of objects like that? If so, it would make sense to show a starting point with more than one object, and it's a matter of just creating the destination object from the source object in the `map` callback. – T.J. Crowder Nov 12 '22 at 10:30
  • [{"user_id":"10","dates":["11/21/2022","11/25/2022"]}] = this is the original output – Sharmae Reyes Nov 12 '22 at 10:32

2 Answers2

2

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

If you just want to console.log to appear in the way you described, this then you just have to access the elements from the array and print them in the way you want.

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[0][0]}': ["${output[0][1][0]}, ${output[0][1][1]}"]`);
Daniel
  • 34
  • 4