Home > Software engineering >  Map a new key-value pair into an array of objects
Map a new key-value pair into an array of objects

Time:04-22

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?

CodePudding user response:

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;
  };
}

CodePudding user response:

You can simply change the map in addUserStatus to forEach, where you can mutate the entries and add the logged-in property:

addUserStatus() {
  this.userData.forEach((data, i) => {
    data["logged-in"] = this.loggedInUser[i].self;
  };
}
  • Related