简体   繁体   中英

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

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,
    };
});

You can use array#map to interchange name and key .

 const input = [{ name: "name1", key: "12weqw3123123"},{ name: "name2", key: "1231231rasd"}, { name: "name3", key: "sa43214dasd"}], result = input.map(({name, key}) => ({name: key, key: name})); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM