如何将 2 个数组连接到节点中的单个 json/array
How to join 2 array into a single json/array in node
我在节点中有 2 个数组。
['3', '7' ]
[ 'Circulatory and Cardiovascular', 'Respiratory' ]
我想产生如下结果。
{{"id": "3","name":"Circulatory and Cardiovascular"},{"id": "7","name":"Respiratory"}}
我假设你想创建这个数据结构(数组而不是散列):
[{"id": "3","name":"Circulatory and Cardiovascular"},{"id": "7","name":"Respiratory"}]
在这种情况下,您可以像这样使用 lodash:
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);
很抱歉,输出中是一个数组,但它更容易。 你可以这样做:
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]});
}
输出:
[ { id: '3', name: 'Circulatory and Cardiovascular' },
{ id: '7', name: 'Respiratory' } ]
我不确定这是个好主意,但你可以将你的新数组转换成这样的对象:
var newObject = newArray.reduce(function(o, v, i) {
o[i] = v;
return o;
}, {});
输出:
{ '0': { id: '3', name: 'Circulatory and Cardiovascular' },
'1': { id: '7', name: 'Respiratory' } }
或者另一种方式:
Object.setPrototypeOf(newArray, Object.prototype); // Now it's an object
输出:
Object [
{ id: '3', name: 'Circulatory and Cardiovascular' },
{ id: '7', name: 'Respiratory' } ]
希望对您有所帮助!
我在节点中有 2 个数组。
['3', '7' ]
[ 'Circulatory and Cardiovascular', 'Respiratory' ]
我想产生如下结果。
{{"id": "3","name":"Circulatory and Cardiovascular"},{"id": "7","name":"Respiratory"}}
我假设你想创建这个数据结构(数组而不是散列):
[{"id": "3","name":"Circulatory and Cardiovascular"},{"id": "7","name":"Respiratory"}]
在这种情况下,您可以像这样使用 lodash:
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);
很抱歉,输出中是一个数组,但它更容易。 你可以这样做:
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]});
}
输出:
[ { id: '3', name: 'Circulatory and Cardiovascular' },
{ id: '7', name: 'Respiratory' } ]
我不确定这是个好主意,但你可以将你的新数组转换成这样的对象:
var newObject = newArray.reduce(function(o, v, i) {
o[i] = v;
return o;
}, {});
输出:
{ '0': { id: '3', name: 'Circulatory and Cardiovascular' },
'1': { id: '7', name: 'Respiratory' } }
或者另一种方式:
Object.setPrototypeOf(newArray, Object.prototype); // Now it's an object
输出:
Object [
{ id: '3', name: 'Circulatory and Cardiovascular' },
{ id: '7', name: 'Respiratory' } ]
希望对您有所帮助!