How to join 2 array into a single json/array in node

63 Views Asked by At

I have 2 arrayes in node .

['3', '7' ]

[ 'Circulatory and Cardiovascular', 'Respiratory' ]

I want to produce result as below.

{{"id": "3","name":"Circulatory and Cardiovascular"},{"id": "7","name":"Respiratory"}}

2

There are 2 best solutions below

0
On BEST ANSWER

I assume you want to create this data structure (array instead of hash):

[{"id": "3","name":"Circulatory and Cardiovascular"},{"id": "7","name":"Respiratory"}]

In that case you can use lodash like this:

var _ = require('lodash');

var a1 = ['3', '7' ];
var a2 = [ 'Circulatory and Cardiovascular', 'Respiratory' ];

var obj = _.merge(_.map(a1, function (o) { return { id : o } }), _.map(a2, function (o) { return { name : o } }))

console.log(obj);
0
On

I'm sorry that's an array in output but it's easier. You could do this:

var idArray = ['3', '7' ];
var nameArray = [ 'Circulatory and Cardiovascular', 'Respiratory' ];
var newArray = [];

for (var i = 0; i < idArray.length; i++) {
    newArray.push({"id": idArray[i], "name": nameArray[i]});
}

Output:

[ { id: '3', name: 'Circulatory and Cardiovascular' },
  { id: '7', name: 'Respiratory' } ]

I'm not sure that's a great idea, but you can convert your new array into an object like this:

var newObject = newArray.reduce(function(o, v, i) {
  o[i] = v;
  return o;
}, {});

Output:

{ '0': { id: '3', name: 'Circulatory and Cardiovascular' },
  '1': { id: '7', name: 'Respiratory' } }

Or another way:

Object.setPrototypeOf(newArray, Object.prototype); // Now it's an object

Output:

Object [
  { id: '3', name: 'Circulatory and Cardiovascular' },
  { id: '7', name: 'Respiratory' } ]

Hope this help !