I have Java script array like this:
JavaScript
x
28
28
1
arr = [
2
{
3
"email": "info@gmail.com",
4
"phoneNumber": "++255 638-1527",
5
},
6
{
7
"email": "@gmail.com",
8
"phoneNumber": "+255 532-1587",
9
},
10
{
11
"email": "@gmail.com",
12
"phoneNumber": "+255 613-1587",
13
"info": [
14
{
15
"date": "2022-02-19",
16
"count": 1
17
},
18
{
19
"date": "2022-03-17",
20
"count": 9
21
},
22
{
23
"date": "2021-02-10",
24
"count": 10
25
}]
26
}
27
]
28
I need to convert above array of objects arr
into object with key-value pair like below
JavaScript
1
29
29
1
arr =
2
3
{
4
"+255 638-1527":{
5
"email": "info@gmail.com",
6
"phoneNumber": "+255 638-1527",
7
},
8
"+255 532-1587":{
9
"email": "@gmail.com",
10
"phoneNumber": "+255 532-1587",
11
},
12
"+255 613-1587":{
13
"email": "@gmail.com",
14
"phoneNumber": "+255 613-1587",
15
"info": [
16
{
17
"date": "2022-02-19",
18
"count": 1
19
},
20
{
21
"date": "2022-03-17",
22
"count": 9
23
},
24
{
25
"date": "2021-02-10",
26
"count": 10
27
}]
28
}
29
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:
JavaScript
1
7
1
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}]}];
2
3
const result = Object.fromEntries(arr.map(item =>
4
[item.phoneNumber, item]
5
));
6
7
console.log(result);