drunkdolphin
drunkdolphin

Reputation: 797

How to rearrange different type of associative array in Typescript?

I want to rearrange to different type of associative array to extract same property. So I tried to make sample code below.

const array1 = [{name:'john',age:25},{name:'Bob',age:33}];
const array2 = [{name:'Jen',age:35,id:1},{name:'Mera',age:31,id:2}];
const array3 = array1.concat(array2);
console.log(array3)

and this code reuld is like that.

0: {name: "john", age: 25}
1: {name: "Bob", age: 33}
2: {name: "Jen", age: 35,id:1}
3: {name: "Mera", age: 31,id:2}

my goal is just below.

0: {name: "john"}
1: {name: "Bob"}
2: {name: "Jen"}
3: {name: "Mera"}

Could someone adivise me, please?

Upvotes: 0

Views: 52

Answers (1)

jcalz
jcalz

Reputation: 329013

If you just want the values to have a name property, then you should just map() the array elements to ones with just a name property. For example:

const array3 = [...array1, ...array2].map(({ name }) => ({ name }));

console.log(array3); 
// [ { "name": "john" }, { "name": "Bob" }, { "name": "Jen" }, { "name": "Mera" } ] 

Here I'm using spread in array literals instead of concat(), and destructuring assignment for the object mapping. If those are weird looking, you could rewrite it as:

const array4 = array1.concat(array2).map(value => ({ name: value.name }));

which does pretty much the same thing. Hope that helps; good luck!

Playground link

Upvotes: 2

Related Questions