简体   繁体   English

如何从数组中的对象的某些键中提取值

[英]How to extract values from certain keys from objects that are in an array

I have this array of objects: var array = [{name: "Tom", id: 123}, {name: "chris", id: 1234}, {name: "Simon", id: 111}];我有这个对象数组: var array = [{name: "Tom", id: 123}, {name: "chris", id: 1234}, {name: "Simon", id: 111}];

I want to iterate through the 3 objects in the array and extract the name of each one, and then push that name into a new array.我想遍历数组中的 3 个对象并提取每个对象的名称,然后将该名称推送到一个新数组中。

This is what I thought would work:这就是我认为会起作用的:

 var array = [{name: "Tom", id: 123}, {name: "chris", id: 1234}, {name: "Simon", id: 111}]; var newArrayOfNames = []; Object.values(array).forEach(function(name){ newArrayOfNames.push(name); }); console.log(newArrayOfNames);

you can try this:你可以试试这个:

    var array = [{name: "Tom", id: 123}, {name: "chris", id: 1234}, {name: "Simon", id: 111}];
    var newArrayOfNames = [];
    array.forEach(function(item) {
      newArrayOfNames.push(item.name);
    });
    console.log(newArrayOfNames);

A small change to your code:对代码的一个小改动:

 var array = [{name: "Tom", id: 123}, {name: "chris", id: 1234}, {name: "Simon", id: 111}]; var newArrayOfNames = []; Array.prototype.forEach.call(array, function(o){ newArrayOfNames.push(o.name); }); console.log(newArrayOfNames);

let array = [{name: "Tom", id: 123}, {name: "chris", id: 1234}, {name: "Simon", id: 111}];
let names = []
for(let person of array) {
    names.push(person.name)
}

This should work, it takes the name attribute from the "person", which is in this case an entry in your array.这应该可以工作,它从“person”中获取 name 属性,在这种情况下,它是数组中的一个条目。

A small change in your existing code would have worked:对现有代码稍作改动即可:

 var array = [{name: "Tom", id: 123}, {name: "chris", id: 1234}, {name: "Simon", id: 111}]; var newArrayOfNames = []; Object.values(array).forEach(function(person){ // note that person is the object on each iteration of array newArrayOfNames.push(person.name); // object has property called name }); console.log(newArrayOfNames); // => [ "Tom", "chris", "Simon" ]

This is the perfect use case for a .reduce() , whose goal is:这是.reduce()的完美用例,其目标是:

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value. reduce() 方法对累加器和数组中的每个元素(从左到右)应用一个函数以将其减少为单个值。

In your case, you want to accumulate all of the names and put them into a new Array.在您的情况下,您希望累积所有名称并将它们放入一个新数组中。 Perfect for .reduce() .非常适合.reduce()

Note that the acc argument stands for accumulator, so each time you loop through a person , you make your changes to the accumulator and then pass it to the next loop.请注意, acc参数代表 accumulator,因此每次循环遍历person ,都会对 accumulator 进行更改,然后将其传递给下一个循环。

Note: I would not recommend solving your problem using .forEach() since forEach will make changes directly to your original Array.注意:我不建议使用.forEach()解决您的问题,因为forEach将直接更改您的原始数组。 Any changes you do, will be applied to people , and you will get a new Array back from forEach .您所做的任何更改都将应用于people ,并且您将从forEach获得一个新的 Array 。 This is why methods such as Array.prototype.map/reduce exist!这就是Array.prototype.map/reduce等方法存在的原因!

const people = [
  { name: "Tom", id: 123} ,
  { name: "chris", id: 1234} ,
  { name: "Simon", id: 111 },
];

const names = people.reduce((acc, person) => {
  acc.push(person.name);

  return acc;
}, []);

IMHO, the best approach as of 2021 is as follows:恕我直言,截至 2021 年的最佳方法如下:

let array = [
    {
        name: "Tom",
        id: 123
    },
    {
        name: "chris",
        id: 1234
    },
    {
        name: "Simon",
        id: 111
    }
];
// Use the Array's map function to transform the elements of the array into something else
let newArrayOfNames = array.map( pValue => pValue.name );

console.log( newArrayOfNames );

The map 's documentation states: map的文档说明:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. map()方法创建一个新数组,其中填充了对调用数组中的每个元素调用提供的函数的结果。

This would be the most appropriate way (Provided you don't support IE anymore or you use a transpiler) since both arrays are of the same length.这将是最合适的方式(假设您不再支持 IE 或您使用转译器),因为两个数组的长度相同。

If you need to omit elements I'd use the filter function for omitting those elements first and then the map function, and although that requires to iterate once through the original array and once through the filtered array, the purpose of the code is clearer for the reader of the code.如果您需要省略元素,我会先使用filter函数来省略这些元素,然后是map函数,尽管这需要遍历原始数组和过滤数组一次,但代码的目的更清晰代码的读者。 Another approach is to use reduce to create another array and filter the elements in the callback given to reduce (not pushing them into the new array), this will only traverse the original array once but may lack clarity for readers depending on your code.另一种方法是使用reduce创建另一个数组并过滤给定reduce的回调中的元素(而不是将它们推送到新数组中),这只会遍历原始数组一次,但根据您的代码,读者可能不清楚。

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

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