I have Java script array like this:
arr = [ { "email": "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e070008012e09030f0702400d0103">[email protected]</a>", "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": "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2940474f46694e44484045074a4644">[email protected]</a>", "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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0