从两个数组创建一个对象

时间:2018-02-21 14:51:21

标签: javascript arrays object lodash javascript-objects

我有两个数组

let arr1 = [1, 2, 3, 4, 5];
let arr2 = [6, 7, 8, 9, 0];

我使用.map

从他们创建了一个对象
let labels = arr1.map(value => ({'y': value}));
let series = arr2.map(value => ({'x': value}));

使用来自lodash

_.merge合并对象
let mergeData = _.merge({}, series2, labels2);

结果与此类似:

{x: 1, y: 25},
{x: 2, y: 38},
{x: 3, y: 24},
{x: 4, y: 60},
{x: 5, y: 22}

现在我要显示的是一个对象数组(在这种情况下,它只显示数组中的一个对象),如下所示:

graphs: [
  {
    label: 'area 1',
    values: [
      {x: 1, y: 25},
      {x: 2, y: 38},
      {x: 3, y: 24},
      {x: 4, y: 60},
      {x: 5, y: 22}
    ]
  },
]

任何想法?

3 个答案:

答案 0 :(得分:1)

我将数组中的对象连接起来:

let mergeData = [].concat(_.merge({}, series2, labels2));

答案 1 :(得分:1)

您可以使用array#map并创建值对象。

let arr1 = [1, 2, 3, 4, 5],
    arr2 = [6, 7, 8, 9, 0],
    values = arr1.map((x, i) => ({x,y: arr2[i]})),
    output = { graphs: [{ label: 'area 1', values }]};
console.log(output);

答案 2 :(得分:0)

您可以使用_.zip()将两个数组都转换为成对的数组[[1, 6], [2, 7],...],然后映射成对的数组,并使用_.zipObject()用{{1}创建对象}属性:

['x', 'y']
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [6, 7, 8, 9, 0];

const result = _.map(
  _.zip(arr1, arr2), // combine each column to a pair [1, 6],  [2, 7], etc...
  _.partial(_.zipObject, ['x', 'y']) // create a function that converts each pair to an object
)

console.log(result)

相关问题