Skip to content
Advertisement

Change property name from an array of object javascript/typescript

I have the following array of obect lets call it “myArray”:

0: { name: "name1", key: "12weqw3123123"}
1: { name: "name2", key: "1231231rasd"}
2: { name: "name3", key: "sa43214dasd"}

What I would like to achieve is to switch the properties naming form name to key and the opposite so the final result is something like that:

0: { key: "name1", name: "12weqw3123123"}
1: { key: "name2", name: "1231231rasd"}
2: { key: "name3", name: "sa43214dasd"}

I tried with

  const { name } = myArray;
  const newResp = { key: name };

but its undefined and I tried also with

const newArray = [...myArray].map((r: { name: any; key: any }) => {
    r.name = r.key;
    delete r.key;
  });

any suggestions? Thanks

Advertisement

Answer

You could handle it with a forEach:

myArray.forEach(item => {
    let tmp = item.key;
    item.key = item.name;
    item.name = tmp;
});

It can technically work with map as well, but in general map should be used when you want to create a new array, and not to update in-place.

let newArray = myArray.map(item => {
    return {
        key: item.name,
        name: item.key,
    };
});
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement