Skip to content
Advertisement

How to rearrange array of objects into object of objects in node js?

I have Java script array like this:

arr =   [
            {
                "email": "info@gmail.com",
                "phoneNumber": "++255 638-1527",
            },
            {
                "email": "@gmail.com",
                "phoneNumber": "+255 532-1587",
            },
            {
                "email": "@gmail.com",
                "phoneNumber": "+255 613-1587",
                "info": [
                    {
                        "date": "2022-02-19",
                        "count": 1
                    },
                    {
                        "date": "2022-03-17",
                        "count": 9
                    },
                    {
                        "date": "2021-02-10",
                        "count": 10
                    }]
           }
    ]

I need to convert above array of objects arr into object with key-value pair like below

arr = 

        {
            "+255 638-1527":{
                "email": "info@gmail.com",
                "phoneNumber": "+255 638-1527",
            },
            "+255 532-1587":{
                "email": "@gmail.com",
                "phoneNumber": "+255 532-1587",
            },
            "+255 613-1587":{
                "email": "@gmail.com",
                "phoneNumber": "+255 613-1587",
                "info": [
                    {
                        "date": "2022-02-19",
                        "count": 1
                    },
                    {
                        "date": "2022-03-17",
                        "count": 9
                    },
                    {
                        "date": "2021-02-10",
                        "count": 10
                    }]
           }

I need the it like this JSON, in the form of key-value pair. How can I achieve this?

I need the data like this in order to render the output, can someone please help me with this?

Advertisement

Answer

Use Object.fromEntries like this:

const arr = [{"email": "info@gmail.com","phoneNumber": "++255 638-1527",},{"email": "@gmail.com","phoneNumber": "+255 532-1587",},{"email": "@gmail.com","phoneNumber": "+255 613-1587","info": [{"date": "2022-02-19","count": 1},{"date": "2022-03-17","count": 9},{"date": "2021-02-10","count": 10}]}];
    
const result = Object.fromEntries(arr.map(item =>
    [item.phoneNumber, item]
));

console.log(result);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement