Create new JSON array from given JSON array in JavaScript

For example I have an array like this

{
  "employees": [
    { "name": "Ram", "email": "[email protected]", "age": 23 },
    { "name": "Shyam", "email": "[email protected]", "age": 28 },
    { "name": "John", "email": "[email protected]", "age": 33 },
    { "name": "Bob", "email": "[email protected]", "age": 41 }
  ]
}

If I want an array like {"sam","shyan","john","bob"} I got it , just using map

arrayname.map((item) => item.name);

BUT if I want an array like this from above array

{
  "employees": [
    { "name": "Ram", "email": "[email protected]" },
    { "name": "Shyam", "email": "[email protected]" },
    { "name": "John", "email": "[email protected]" },
    { "name": "Bob", "email": "[email protected]" }
  ]
}

How can I do that? Thank you a lots

Upvotes: 0

Views: 69

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370729

For the general situation where you want to remove one property from all objects in an array, you can destructure that property and collect the rest with rest syntax.

const employees = [    
    {"name":"Ram", "email":"[email protected]", "age":23},    
    {"name":"Shyam", "email":"[email protected]", "age":28},  
    {"name":"John", "email":"[email protected]", "age":33},    
    {"name":"Bob", "email":"[email protected]", "age":41}   
];

const result = employees.map(({ age, ...rest }) => rest);
console.log(result);

If you want to keep a number of them, then destructure those and list them in the returned object.

const employees = [    
    {"name":"Ram", "email":"[email protected]", "age":23},    
    {"name":"Shyam", "email":"[email protected]", "age":28},  
    {"name":"John", "email":"[email protected]", "age":33},    
    {"name":"Bob", "email":"[email protected]", "age":41}   
];

const result = employees.map(({ name, email }) => ({ name, email }));
console.log(result);

Upvotes: 3

Guilherme A C Zaluchi
Guilherme A C Zaluchi

Reputation: 69

As you said:

array.employees.map(function(item, _i, _array){
  return item.name;
});

Would get you an array in the form:

[
  "sam", "shyan", "john", "bob"
]
// But not {"sam", "shyan", "john", "bob"}. These are other things.

As the type of item you want is in the form:

{ name: "Ram", email: "[email protected]" }

You want your function to return an object for each item it receives. There are (maybe really) thousands of ways to do so. Let's try something simple:

function(item, _i, _array){
  // returning an object
  return {
    // the 'name' property takes the value from the item
    name: item.name,
    // same for the 'email'
    email: item.email
  };
}

Upvotes: 1

Related Questions