[英]Create an object from two arrays
I two have arrays我有两个数组
let arr1 = [1, 2, 3, 4, 5];
let arr2 = [6, 7, 8, 9, 0];
i created an object from them using .map
我使用
.map
从它们创建了一个对象
let labels = arr1.map(value => ({'y': value}));
let series = arr2.map(value => ({'x': value}));
and merged object using _.merge
from lodash并使用合并对象
_.merge
从lodash
let mergeData = _.merge({}, series2, labels2);
result looks similar to this:结果与此类似:
{x: 1, y: 25},
{x: 2, y: 38},
{x: 3, y: 24},
{x: 4, y: 60},
{x: 5, y: 22}
Now what i would like to display is an array of objects (in this case it will display just one object inside array) which looks like one below:现在我想显示的是一组对象(在这种情况下,它将只显示数组内的一个对象) ,如下所示:
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}
]
},
]
any ideas?有什么想法吗?
You can use array#map
and create the values object.您可以使用
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);
我将在数组中连接对象,如下所示:
let mergeData = [].concat(_.merge({}, series2, labels2));
You can use _.zip()
to convert both arrays to an array of pairs [[1, 6], [2, 7],...]
, then map the array of pairs, and use _.zipObject()
to create an object with the ['x', 'y']
properties:您可以使用
_.zip()
将两个数组转换为对的数组[[1, 6], [2, 7],...]
,然后映射对的数组,并使用_.zipObject()
到创建一个具有['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)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.