ShocKwav3_
ShocKwav3_

Reputation: 1760

Construct an array of objects with two specific object value pair from another array of objects

Let's say there is an array of object.

let source = [
 {'name': 'a', age: '10', id: 'a0'},
 {'name': 'b', age: '12', id: 'b2'},
 {'name': 'c', age: '14', id: 'c4'},
 {'name': 'd', age: '16', id: 'd6'},
 {'name': 'e', age: '18', id: 'e8'}
]

What I am trying to achieve is create a new array which will consist specific two key-value pair. Example result,

[
 {'name': 'a', id: 'a0'},
 {'name': 'b', id: 'b2'},
 {'name': 'c', id: 'c4'},
 {'name': 'd', id: 'd6'},
 {'name': 'e', id: 'e8'}
]

Help would be much appreciated.

Upvotes: 2

Views: 49

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386604

You could use destructuring assignment and Array#map for a new array of new objects.

let source = [{ name: 'a', age: '10', id: 'a0' }, { name: 'b', age: '12', id: 'b2' }, { name: 'c', age: '14', id: 'c4' }, { name: 'd', age: '16', id: 'd6' }, { name: 'e', age: '18', id: 'e8' }],
    result = source.map(({ name, id }) => ({ name, id }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 4

kukkuz
kukkuz

Reputation: 42352

Use Array.prototype.map function - see demo below:

let source = [{ name: 'a', age: '10', id: 'a0' }, { name: 'b', age: '12', id: 'b2' }, { name: 'c', age: '14', id: 'c4' }, { name: 'd', age: '16', id: 'd6' }, { name: 'e', age: '18', id: 'e8' }]

let result = source.map(function(e){
  return {
    name: e.name,
    id  : e.id
  }
});

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

Upvotes: 3

Related Questions