-1

I have an object that I receive from an api, and each object's length are similarly long.
now, it does have a key fname and lname and I want it to become just name. I don't want to manually create an empty array and push a new one there just to change fname and lname into name.

Is there anyway I can achieve this without looping through the object and manually pushing it?

darogo
  • 51
  • 1
  • 7
  • can you provide the dummy input data for better clarity? – gorak Jun 16 '20 at 14:26
  • check this: https://stackoverflow.com/questions/4647817/javascript-object-rename-key – Karim Jun 16 '20 at 14:30
  • [change property name](https://stackoverflow.com/questions/8483425/change-property-name) or [Changing the key name in an array of objects?](https://stackoverflow.com/questions/6809659/changing-the-key-name-in-an-array-of-objects) – Andreas Jun 16 '20 at 14:30

1 Answers1

1

You can destructure the object while mapping it, here I have created a dummy data, let me know if this is something what you need:

var array=[{id:1, fname:'Bob', lname: 'Alice', someotherkey:'key'}];
var result = array.map(({fname, lname, ...rest})=>({name:fname+' '+lname, ...rest}));

console.log(result);
gorak
  • 5,233
  • 1
  • 7
  • 19
  • Instead of adding just another answer on "how to rename a property", look for a dupe and VtC. Your approach with `.map()` and the spread syntax will most likely be part of those duplicates (see the examples in the comments below the question) – Andreas Jun 16 '20 at 14:42