如何将数组插入到数组内的对象中?对于 ng2-charts / Charts.js

How to insert arrays into objects that are inside an array? For ng2-charts / Charts.js

假设我有 2 个数组:

var array1 = [1,1,1];
var array2 = [2,2,2];

如何使用下面显示的 2 个对象创建父数组?

(我正在尝试将上面给定的数组插入到具有 2 个对象的父数组中,但我仍然需要创建对象,以便它们包含显示的键。这是为了符合 ng2-charts ChartDataSets 类型。)

// below is what I'm trying to accomplish, but I only have the 2 arrays above so far
[
  { data : array1, label: 'some label1' },
  { data : array2, label: 'some label2' },
]

通过使用下面的语句列表,您可以实现上面的对象数组。

var array1 = [1,1,1];
var array2 = [2,2,2];
var arrObj = [];
var tempObj = {};
tempObj.data = array1;
tempObj.lable = "test1";
arrObj.push(tempObj);
tempObj.data = array2;
tempObj.lable = "test1";
arrObj.push(tempObj);

"arrObj" 有您想要的示例输出

使用映射和传播运算符

const array1 = [1,1,1];
const array2 = [2,2,2];

const parentArr = [
  { label: 'some label1' },
  { label: 'some label2' },
]

function a (array) {
  return parentArr1 = parentArr.map(it => {
    return {...it, data: array }
  })
}

console.log(a(array1))
console.log(a(array2))

let arr1 = [1, 1, 1];
let arr2 = [2, 2, 2];
let reqArray = [arr1, arr2].map((ele, ind) => {
  return {
    data: ele,
    label: `some label${ind+1}`
  }
});
console.log(reqArray)