I would like to add a new key-value pair to all objects within my data. The structure looks like this:
userData: [ { "id": 1, "name": "John Doe", "email": "xyz.com" }, { "id": 2, "name": "Jane Doe", "email": "zzz.com" }, { "id": 3, "name": "Anne Doe", "email": "yyy.com" } ]
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.
const activeUser = await this.userService.getUserProfile().toPromise(); this.currentUser = activeUser.id; this.loggedInUser = this.getAccountDetails.map(user => ({ self: this.currentUser === user.id }) )
Then, I would like to push these key-value pairs into userData.
loggedInUser: { self: boolean }[]; addUserStatus() { this.userData.map((data, i) => ({ ...data, "logged-in": this.loggedInUser[i].self })) }
What I would like to achieve:
userData: [ { "id": 1, "name": "John Doe", "email": "xyz.com", "logged-in": true }, { "id": 2, "name": "Jane Doe", "email": "zzz.com", "logged-in": false }, { "id": 3, "name": "Anne Doe", "email": "yyy.com", "logged-in": false } ]
What did I do wrong here?
Advertisement
Answer
map
returns new data, so your function should look something like this
loggedInUser: { self: boolean }[]; addUserStatus() { const temp = this.userData.map((data, i) => ({ ...data, "logged-in": this.loggedInUser[i].self })) this.userData = temp }
If you want to modify this.userData
directly, you can use other methods like forEach
addUserStatus() { this.userData.forEach((data, i) => { data["logged-in"] = this.loggedInUser[i].self; }; }