0

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.

1

2 Answers 2

5

You can do it with .map(),

var res = json.map(function(itm){
  return {id:itm.id, name:itm.name}
});
Sign up to request clarification or add additional context in comments.

1 Comment

FYI - in ES2015+ you can do var res = json.map(({id, name}) => ({id, name}));
2

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

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.