1

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

let labels = arr1.map(value => ({'y': value}));
let series = arr2.map(value => ({'x': value}));

and merged object using _.merge from 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?

1
  • Do you want to loop over the object['values'] field? Commented Feb 21, 2018 at 14:57

3 Answers 3

2

You can use array#map and create the values object.

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);

Sign up to request clarification or add additional context in comments.

Comments

1

I'd concat objects inside of an array as such:

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

Comments

1

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:

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.