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

135
Views
Is there a quicker way to copy a value in a key of data object to a new key in the same data object in javascript?

I'm experimenting with how I can make my code more concise when I have a piece of an array of objects received from an API endpoint. This is the initial variabel:

let stringOptionsOutlet = [];

Then I want to make a new key called "value". This is how I normally do (which I think is okey but I believe there must be some disadvantages in comparison with other techniques you might come up with):

stringOptionsOutlet = [...response.data.outlet]; // 1. this is the data I get from an API endpoint, I copy it with the spread operator
stringOptionsOutlet.map((v) => return { ...v, value: "" }; ); // 2. then I make the same new value in every single data object inside the array stringOptionsOutlet
Object.entries(stringOptionsOutlet).forEach((e) => {
   e[1].value = e[1].id; // 3. copy the value of id to the new key
});

The data before I map the data:

[ 
  {
   label: "A1-1",
   id: "1",
  },
  {
   label: "B2-1",
   id: "4",
  },
]

After the mapping (step number 2 and number 3):

[ 
  {
   label: "A1-1",
   id: "1",
   value: "1",
  },
  {
   label: "B2-1",
   id: "4",
   value: "1"
  },
]

Could you also please explain the benefits and shortcomings of the techniques? Thank you.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

What you're doing will work but there are certainly some unnecessary steps as written. There's no need to copy the API response data into an array and then change the array contents when you can map the API response itself.

// You can do steps 1 2 and 3 all in 1 .map()
const stringOptionsOutlet = response.data.outlet.map(v => {
    return {
        ...v,
        value: v.id
    }
})

The downside of doing it all in 1 way is that if you want to do some more complex logic that single .map call could get very cluttered and maybe it'd be simpler to introduce a separate step, with the caveat that you'd then process the data a second time.

about 4 years ago · Juan Pablo Isaza Report

0

Try this:

stringOptionsOutlet.map((v) => ({ ...v, value: v.id }));
about 4 years ago · Juan Pablo Isaza 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!