I want to achieve this format. As you can see on the output there’s a bracket but I want to get only the ’10’: ["11/21/2022", "11/25/2022"] or this one.
{
'10': ["11/21/2022", "11/25/2022"]
}
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 :
You can only do this if the array has just one entry. Otherwise, how would you know which array element to use?
Then just create it directly, map creates an array, not an object:
const [{ user_id, dates }] = data;
const output = {
[user_id]: dates,
};
Live Example:
const data = [
{
user_id: "10",
dates: ["11/21/2022", "11/25/2022"],
},
];
const [{ user_id, dates }] = data;
const output = {
[user_id]: dates,
};
console.log(output);
Or without the initial destructuring:
const output = {
[data[0].user_id]: data[0].dates,
};
Live Example:
const data = [
{
user_id: "10",
dates: ["11/21/2022", "11/25/2022"],
},
];
const output = {
[data[0].user_id]: data[0].dates,
};
console.log(output);