Home > Enterprise >  Is there a quicker way to copy a value in a key of data object to a new key in the same data object
Is there a quicker way to copy a value in a key of data object to a new key in the same data object

Time:09-17

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.

CodePudding user response:

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.

CodePudding user response:

Try this:

stringOptionsOutlet.map((v) => ({ ...v, value: v.id }));
  • Related