将多个数组合并为一个带有字段的数组

Combine multiple arrays to a single with fields

本文关键字:数组 一个 字段 合并      更新时间:2023-09-26
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)

https://jsfiddle.net/3s8rasm6/

您可以在一个数组中循环访问两个数组。||运算符这样做,如果值未定义,它将 ne 替换为 null

for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  mList.push({
    clients: _ref[_i] || null,
    project: _ref2[_i] || null
  });
}

同时使用这两个对象。 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);

演示

$(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);
});
你可以

用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
    }
})