0

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

2 Answers 2

1

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,
    };
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Q: What does CSS class as-console-wrapper do?
It moves the console output to the top of the div.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.