Nasir Ahmed
Nasir Ahmed

Reputation: 521

Pick certain item from javascript array of objects

For example I have an array of object

var json = [
  {
    id: 23,
    name: 'zyan doe',
    email: '[email protected]'
    job_titlte: 'software engineer',
  },
  {
    id: 24,
    name: 'john doe',
    email: '[email protected]'
    job_titlte: 'support engineer',
  },
  {
    id: 25,
    name: 'jane doe',
    email: '[email protected]'
    job_titlte: 'software engineer',
  }
];

I want this array with only id and names, like

[
  {
    id: 23,
    name: 'zyan doe'
  },
  {
    id: 24,
    name: 'john doe'
  },
  {
    id: 25,
    name: 'jane doe'
  }
]

I need to do it with pure javascript. I have searched for a while but could not figure out. How to do it.

Upvotes: 0

Views: 114

Answers (2)

duncanhall
duncanhall

Reputation: 11431

You can use the Array.map() function to 'transform' each item in an array, creating a new array of the the transformed items:

function getOnlyIdAndName(item) {
    return {id:item.id, name:item.name};
}

var newArrayOfTransformedItems = json.map(getOnlyIdAndName);

Upvotes: 2

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You can do it with .map(),

var res = json.map(function(itm){
  return {id:itm.id, name:itm.name}
});

Upvotes: 5

Related Questions