如何最小化对象并从JavaScript中的对象数组构建数组

时间:2017-12-05 06:44:05

标签: javascript arrays

我有一个对象数组,每个对象有大约5个属性和各自的值。我想迭代数组中的每个对象,只从中选择两个属性并重建对象和数组。

例如:

let resArray = [
{"name": "Aaron", "id": 123, "sex": "male", "country": "usa"}, 
{"name": "Bert", "id": 456, "sex": "male", "country": "usa"}, 
{"name": "Brenda", "id": 657, "sex": "female", "country": "canada"}, 
{"name": "Chris", "id": 856, "sex": "male", "country": "usa"}, 
{"name": "Angela", "id": 113, "sex": "female", "country": "columbia"}, 
{"name": "Maria", "id": 569, "sex": "female", "country": "mexico"}];

我想删除"国家"而且"性别"来自对象的属性并保留" name"和" id"属性并重建数组。即,输出应如下:

let outArray = [
{"name": "Aaron", "id": 123}, 
{"name": "Bert", "id": 456}, 
{"name": "Brenda", "id": 657}, 
{"name": "Chris", "id": 856}, 
{"name": "Angela", "id": 113}, 
{"name": "Maria", "id": 569}];

截至目前,我只是使用resArray并遍历整个数组并获得我想要的任何值。但我只是认为我可以最大限度地减少对象,以便清除杂乱。

有人可以帮我解决这个问题吗? 谢谢。

3 个答案:

答案 0 :(得分:5)

您可以将array#mapobject#destructuring一起使用。使用array#map遍历您的对象并获取nameid值并创建一个新对象。



let resArray = [ {"name": "Aaron", "id": 123, "sex": "male", "country": "usa"}, {"name": "Bert", "id": 456, "sex": "male", "country": "usa"}, {"name": "Brenda", "id": 657, "sex": "female", "country": "canada"}, {"name": "Chris", "id": 856, "sex": "male","country": "usa"}, {"name": "Angela", "id": 113, "sex": "female", "country": "columbia"}, {"name": "Maria", "id": 569, "sex": "female", "country": "mexico"}];
let result = resArray.map(({name, id}) => ({name, id}));
console.log(result);




答案 1 :(得分:1)

使用Array#map功能,根据项目

创建所需的形状



let resArray = [
   {"name": "Aaron", "id": 123, "sex": "male", "country": "usa"}, 
   {"name": "Bert", "id": 456, "sex": "male", "country": "usa"}, 
   {"name": "Brenda", "id": 657, "sex": "female", "country": "canada"}, 
   {"name": "Chris", "id": 856, "sex": "male", "country": "usa"}, 
   {"name": "Angela", "id": 113, "sex": "female", "country": "columbia"}, 
   {"name": "Maria", "id": 569, "sex": "female", "country": "mexico"}
];

let mappedArr = resArray.map(item => ({name: item.name, id: item.id}));

console.log(mappedArr);




此外,您可以在参数列表中破坏参数item并获得所需的结果

let mappedArr = resArray.map(({id, name}) => ({name, id}));

答案 2 :(得分:0)

您只需使用.map(),如下所示 -

let resArray = [
   {"name": "Aaron", "id": 123, "sex": "male", "country": "usa"}, 
   {"name": "Bert", "id": 456, "sex": "male", "country": "usa"}, 
   {"name": "Brenda", "id": 657, "sex": "female", "country": "canada"}, 
   {"name": "Chris", "id": 856, "sex": "male", "country": "usa"}, 
   {"name": "Angela", "id": 113, "sex": "female", "country": "columbia"}, 
   {"name": "Maria", "id": 569, "sex": "female", "country": "mexico"}
];

let outArray = resArray.map(item => ({name: item.name, id: item.id}));

console.log(JSON.stringify(outArray));