2

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.

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

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.