Returning subset of properties from an array of objects

巧了我就是萌 提交于 2020-06-17 04:23:09

问题


I have an array of objects like

var array = [{date:'01/01/2017',value1:200,value2:300,value3:400}]

I am trying to get a subset of the object properties like var

var newArray = [['01/01/2017',200],['01/01/2017',200],['01/01/2017',200]......]

I do not want an array like this

[[date:'',value2:],[date:'',value2:],[date:'',value13:]]

But just directly a 2 D array from array of objects.

Currently I am doing a for each on my array of objects and pushing the required properties in to an array an returning that array.

I was looking for map function may be if that can work but this does not work with map

array.map(function(item){ 
return {
      item.date, item.value1
       }
});

Kindly suggest if there is any other function to do this without looping over?

Thanks


回答1:


You should use map for this, you were almost there. This will sort you out:

array.map(function(item){ return [item.date,item.value1]});



回答2:


You need to put the values in an array & map method will do rest of the work

var array = [{
  date: '01/01/2017',
  value1: 200,
  value2: 300,
  value3: 400
}, {
  date: '01/01/3017',
  value1: 500,
  value2: 300,
  value3: 400
}];
var m = array.map(function(item) {
  return [item.date, item.value1]
})

console.log(m)
[['01/01/2017',200],['01/01/2017',200]]


来源:https://stackoverflow.com/questions/46902184/returning-subset-of-properties-from-an-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!