I would like to add a new key-value pair to all objects within my data. The structure looks like this:
JavaScript
x
19
19
1
userData:
2
[
3
{
4
"id": 1,
5
"name": "John Doe",
6
"email": "xyz.com"
7
},
8
{
9
"id": 2,
10
"name": "Jane Doe",
11
"email": "zzz.com"
12
},
13
{
14
"id": 3,
15
"name": "Anne Doe",
16
"email": "yyy.com"
17
}
18
]
19
As a new key-value pair, I would like to add “logged-in”: true/false. To get this data, I use another service. And then I map the true/false values into a variable.
JavaScript
1
8
1
const activeUser = await this.userService.getUserProfile().toPromise();
2
this.currentUser = activeUser.id;
3
4
this.loggedInUser = this.getAccountDetails.map(user => ({
5
self: this.currentUser === user.id
6
})
7
)
8
Then, I would like to push these key-value pairs into userData.
JavaScript
1
8
1
loggedInUser: { self: boolean }[];
2
3
addUserStatus() {
4
this.userData.map((data, i) => ({ data,
5
"logged-in": this.loggedInUser[i].self
6
}))
7
}
8
What I would like to achieve:
JavaScript
1
22
22
1
userData:
2
[
3
{
4
"id": 1,
5
"name": "John Doe",
6
"email": "xyz.com",
7
"logged-in": true
8
},
9
{
10
"id": 2,
11
"name": "Jane Doe",
12
"email": "zzz.com",
13
"logged-in": false
14
},
15
{
16
"id": 3,
17
"name": "Anne Doe",
18
"email": "yyy.com",
19
"logged-in": false
20
}
21
]
22
What did I do wrong here?
Advertisement
Answer
map
returns new data, so your function should look something like this
JavaScript
1
9
1
loggedInUser: { self: boolean }[];
2
3
addUserStatus() {
4
const temp = this.userData.map((data, i) => ({ data,
5
"logged-in": this.loggedInUser[i].self
6
}))
7
this.userData = temp
8
}
9
If you want to modify this.userData
directly, you can use other methods like forEach
JavaScript
1
6
1
addUserStatus() {
2
this.userData.forEach((data, i) => {
3
data["logged-in"] = this.loggedInUser[i].self;
4
};
5
}
6