简体   繁体   English

从 JavaScript 中给定的 JSON 数组创建新的 JSON 数组

[英]Create new JSON array from given JSON array in JavaScript

For example I have an array like this例如我有一个这样的数组

{
  "employees": [
    { "name": "Ram", "email": "ram@gmail.com", "age": 23 },
    { "name": "Shyam", "email": "shyam23@gmail.com", "age": 28 },
    { "name": "John", "email": "john@gmail.com", "age": 33 },
    { "name": "Bob", "email": "bob32@gmail.com", "age": 41 }
  ]
}

If I want an array like {"sam","shyan","john","bob"} I got it, just using map如果我想要一个像{"sam","shyan","john","bob"}这样的数组,我知道了,只需使用 map

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

BUT if I want an array like this from above array但是如果我想从上面的数组中得到这样的数组

{
  "employees": [
    { "name": "Ram", "email": "ram@gmail.com" },
    { "name": "Shyam", "email": "shyam23@gmail.com" },
    { "name": "John", "email": "john@gmail.com" },
    { "name": "Bob", "email": "bob32@gmail.com" }
  ]
}

How can I do that?我怎样才能做到这一点? Thank you a lots非常感谢

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.对于要从数组中的所有对象中删除一个属性的一般情况,您可以解构该属性并使用 rest 语法收集 rest。

 const employees = [ {"name":"Ram", "email":"ram@gmail.com", "age":23}, {"name":"Shyam", "email":"shyam23@gmail.com", "age":28}, {"name":"John", "email":"john@gmail.com", "age":33}, {"name":"Bob", "email":"bob32@gmail.com", "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.如果你想保留其中的一些,那么解构它们并将它们列在返回的 object 中。

 const employees = [ {"name":"Ram", "email":"ram@gmail.com", "age":23}, {"name":"Shyam", "email":"shyam23@gmail.com", "age":28}, {"name":"John", "email":"john@gmail.com", "age":33}, {"name":"Bob", "email":"bob32@gmail.com", "age":41} ]; const result = employees.map(({ name, email }) => ({ name, email })); console.log(result);

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: "ram@gmail.com" }

You want your function to return an object for each item it receives.您希望 function 为收到的每个项目返回 object。 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
  };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM