最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Returning subset of properties from an array of objects - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question edited Feb 9, 2019 at 21:48 Bhargav Rao 52.3k29 gold badges127 silver badges141 bronze badges asked Oct 24, 2017 at 4:25 V.BV.B 1,2118 gold badges31 silver badges57 bronze badges 2
  • just fix your syntax error on the array literal you're done. – dandavis Commented Oct 24, 2017 at 4:35
  • Yup that was the mistake :) – V.B Commented Oct 24, 2017 at 5:11
Add a ment  | 

2 Answers 2

Reset to default 6

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

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

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]]

发布评论

评论列表(0)

  1. 暂无评论