2

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 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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 !

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.