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 get the object only from array in javascript?

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 :

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

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