Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

83
Views
Map a new key-value pair into an array of objects

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?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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;
  };
}
about 4 years ago · Santiago Trujillo Report

0

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;
  };
}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!