在对象数组中将对象值转换为 key/value 对

In array of objects turn object values into key/value pair

我有兴趣使用 chartkick,所以我需要将 JS 对象转换为以下格式:

var array = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}]

格式如下:

var arrayOne = [{'01/01/2017': 200}, {'02/01/2017': 220},{'03/01/2017':250}]

如有任何帮助,我们将不胜感激。

使用Array.prototype.map():

const src = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}],

      result = src.map(({date,value1}) => ({[date]: value1}))
      
console.log(result)
.as-console-wrapper{min-height:100%;}

 var array = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}];
    var mappedArray = array.map(item => {
    return {
        [item.date]: item.value1
    }
})

循环数组并将其映射到新结构

试试这个:

 var array = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}]
 
let final_array =  array.map(arr => {
    return {[arr.date] : arr.value1};
 })

console.log(final_array)

你可以试试这个

let sampleArray = [{date:'01/01/2017',value1:200,value2:300,value3:400}, {date:'02/01/2017',value1:220,value2:330,value3:430},{date:'03/01/2017',value1:250,value2:330,value3:420}]


   let finalArray = sampleArray.map(data => ({[data.date]:data.value1}))

console.log(finalArray)

输出将是

[{01/01/2017: 200},{02/01/2017: 220},{03/01/2017: 250}]

如果您想为每个值 1、值 2、...循环执行此操作

var array = [{
  date: '01/01/2017',
  value1: 200,
  value2: 300,
  value3: 400
}, {
  date: '02/01/2017',
  value1: 220,
  value2: 330,
  value3: 430
}, {
  date: '03/01/2017',
  value1: 250,
  value2: 330,
  value3: 420
}]

const numberOfValues = 3;

for (let i = 1; i <= numberOfValues; i++) {
  const mappedArray = array.map(x => {
    const result = {};
    result[x.date] = x["value" + i.toString()];
    return result;
  });
  console.log(mappedArray);
}