first_list = [1,2,3,4]
second_list = ['a','b','c']
如何将这两个数组合并为一个具有两个字段的数组?
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
c = _ref[_i];
mList.push({
clients: c
});
}
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
c = _ref2[_i];
mList.push({
projects: c
});
}
我试过这个,但它只是将对象添加到数组而不是具有两个属性的对象项。
我有
Array [ Object, Object, Object, Object, Object, Object, Object ]
| | | | | | |
clients clients clients clients project project project
虽然我想:
Array [ Object, Object, Object, Object ]
| | | |
clients clients clients clients
+ + + +
projects projects projects projects(null)
答案 0 :(得分:0)
您可以将两个数组循环到一个数组中。 ||
运算符执行此操作,如果值未定义,则将替换为null
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
mList.push({
clients: _ref[_i] || null,
project: _ref2[_i] || null
});
}
答案 1 :(得分:0)
将两个对象一起使用。 https://jsfiddle.net/y19fstp7/
mList = []
first_list = [1,2,3,4];
second_list = ['a','b','c'];
var c, _i, _len, _ref,_ref2;
_ref = first_list;
_ref2 = second_list;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
c = _ref[_i];
mList.push({
clients: _ref[_i],
projects: _ref2[_i]
});
}
console.log(mList);
答案 2 :(得分:0)
您可以使用lodash zipWith:
执行此操作var first_list = [1,2,3,4];
var second_list = ['a','b','c'];
_.zipWith(first_list, second_list, function(first, second){
return {
clients:first || null,
project:second || null
}
})
答案 3 :(得分:0)
$(document).ready(function() {
var first_list = ['1', '2', '3', '4'];
var second_list = ['a', 'b', 'c'];
var clients = [];
var projects = [];
var combined = [];
for (var i = 0; i < first_list.length; i++) {
clients.push({
client: first_list[i]
});
}
for (var i = 0; i < second_list.length; i++) {
projects.push({
project: second_list[i]
});
}
var length = Math.max(first_list.length, second_list.length);
for (var i = 0; i < length; i++) {
combined.push($.extend(clients[i], projects[i]));
}
console.log(clients);
console.log(projects);
console.log(combined);
});