【问题标题】:How to merge 2 javaScript Array?如何合并 2 个 JavaScript 数组?
【发布时间】:2015-09-23 08:45:19
【问题描述】:

我有 2 个数组。

我想将第二个数组的字段值与第一个数组合并。

每个值(即“测试”)都属于第二个数组 (_embedded.profileField.id) 的 _embedded 部分中列出的配置文件字段 id。

第一个数组:配置文件字段

0: Object
field: "FieldLabel1"
id: 1

1: Object
field: "FieldLabel2"
id: 7

2: Object
field: "FieldLabel3"
id: 12

第二个数组:配置文件字段值

0: Object
id: 1
value: "Test"
_embedded: Object
  profileField: Object
    field: "FieldLabel1"
    id: 1

1: Object
id: 2
value: "links"
_embedded: Object
  profileField: Object
    field: "FieldLabel2"
    id: 7

我怎样才能得到一个包含两种信息的数组?

【问题讨论】:

  • 你试过写代码吗?
  • 您是否尝试过搜索 SO?
  • 你有一些原始示例数据吗?

标签: javascript arrays array-merge


【解决方案1】:

使用 Array methods 中的 mapfilter 可以根据需要合并此数组。请参阅以下示例:

/* your arrays definition */
var a = [{
  field: "FieldLabel1",
  id: 1
}, {
 field: "FieldLabel2",
 id: 7
}, {
  field: "FieldLabel3",
  id: 12
}
];

var b = [{
  id: 1,
  value: "Test",
  _embedded: {
  profileField: {
      field: "FieldLabel1",
      id: 1
    }
  }
}, {
  id: 2,
  value: "links",
  _embedded: {
  profileField: {
      field: "FieldLabel2",
      id: 7
    }
  }
}];

/* mergedArray contains merged data from two arrays arranged by id */ 
var mergedArray = a.map(function(aItem){ 
  var value = b.filter(function(bItem) {
    return aItem.id === bItem._embedded.profileField.id;
  }).map(function(item){
    return item.value;
  }).pop();
  aItem.value = value;
  return aItem; 
});

结果是:

margedArray: Array[3]
0: Object
    field: "FieldLabel1"
    id: 1
    value: "Test"
1: Object
    field: "FieldLabel2"
    id: 7
    value: "links"
2: Object
   field: "FieldLabel3"
   id: 12
   value: undefined

【讨论】:

  • 感谢您的示例。我还可以显示没有关联值的空字段吗?
  • 是的,你可以通过迭代第一个(a 在我的例子中)数组。
  • 更新了显示空字段的示例
  • 如果你想了解 mapfilter 最好试试 Jafar Husain 的练习 - reactivex.io/learnrx
【解决方案2】:

您好,只需使用 Jquery,请参阅下面的代码!

对于数组:

var newArray = $.merge(1Array, 2Array);

对象:

var object = $.extend({}, object1, object2);

对于数组:jquery merge array

对象:jquery merge object

谢谢

【讨论】:

  • $.merge 是 jQueery 臃肿的 array.concat - $.merge(Array1, Array2) 并不比 Array1 = Array1.concat(Array2) 以 1/10 的速度和 10 倍的内存完成
  • 你认为这不是你的解决方案,让我删除那个答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-05
  • 2020-06-22
  • 1970-01-01
  • 2019-06-05
  • 2014-10-05
  • 1970-01-01
  • 2022-10-16
相关资源
最近更新 更多