Reputation: 1760
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
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
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