0

I have Java script array like this:

arr =   [
            {
                "email": "[email protected]",
                "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": "[email protected]",
                "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?

1 Answer 1

4

Use Object.fromEntries like this:

const arr = [{"email": "[email protected]","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);

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for answering, I have some other doubt other than this, can you help me with that?, How can I get in touch?
You can always ask a new question on this site. It is the preferred way.
can you please answer this: question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.