【问题标题】:Merge array objects in JavaScript using underscore?使用下划线在 JavaScript 中合并数组对象?
【发布时间】:2018-09-14 22:31:02
【问题描述】:

我有两个数组,我想将它们组合起来以获得共同的结果。 数组应该基于 user_id 而不是索引进行组合 我该怎么做?

数组 1

var array1 = [{
  "name": "Smart Test Pool",
  "user_id": 1,
  "total_time": "15.0",
}];

数组 2

var array2 = [{
  "user_id": 1,
  "total_hours_worked_milliseconds": 60060000,
  "total_time_unshedule_milliseconds": 540000
}];

结果

var result = [{
  "name": "Smart Test Pool",
  "user_id": 1,
  "total_time": "15.0",
  "total_hours_worked_milliseconds": 60060000,
  "total_time_unshedule_milliseconds": 540000
}]; 

【问题讨论】:

  • 在我看来,您想要组合数组元素的属性,而不是数组本身。然后我假设您想将第一个数组的元素 0 与下一个数组的元素 0 组合在一起。对吗?
  • 请使用tour 并通读help center,尤其是How do I ask a good question? 做你的研究,search 以获取有关 SO 的相关主题,然后试一试。 如果您在进行更多研究和搜索后遇到困难并且无法摆脱困境,请发布您的尝试minimal reproducible example,并具体说明您遇到的问题。人们会很乐意提供帮助。祝你好运!
  • 如果你使用 es2015,你可以这样做,var arr1 = ['item1', 'item2']; var arr2 = ['item3', 'item4']; var merge = [...arr1, ...arr2],检查这个:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 假设你有 [{data1}] 和 [{}{data2}] 形式的数据......现在你想要 [{data1 data 2}] .. 这只是其中之一那么可能会有很多这样的......

标签: javascript arrays node.js angular underscore.js


【解决方案1】:

您可以使用以下方法合并对象:

1- 纯 JS 方法:

您可以使用.map().find()Object.assign()

let result = array1.map(o => Object.assign(
    {}, o, array2.find(o2 => o2["user_id"] === o["user_id"])
));

或展开语法:

let result = array1.map((o, i) => (
  {...o,...array2.find(o2 => o2["user_id"] === o["user_id"])}
));

演示:

let array1 = [{
  "name": "Smart Test Pool",
  "user_id": 1,
  "total_time": "15.0",
}];

let array2 = [{
  "user_id": 1,
  "total_hours_worked_milliseconds": 60060000,
  "total_time_unshedule_milliseconds": 540000
}];

let result = array1.map(o => Object.assign(
    {}, o, array2.find(o2 => o2["user_id"] === o["user_id"])
));

console.log(result);

2- 下划线

您可以使用.map().extend() 方法:

let result = _.map(array1, function(o) {
    return _.extend({}, o, _.find(array2, function(o2) {
        return o2["user_id"] === o["user_id"]
    }));
});

演示:

let array1 = [{
  "name": "Smart Test Pool",
  "user_id": 1,
  "total_time": "15.0",
}];

let array2 = [{
  "user_id": 1,
  "total_hours_worked_milliseconds": 60060000,
  "total_time_unshedule_milliseconds": 540000
}];

let result = _.map(array1, function(o) {
	return _.extend({}, o, _.find(array2, function(o2) {
        return o2["user_id"] === o["user_id"]
    }));
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

文档:

【讨论】:

  • 致反对者:我的回答有问题吗?如果是,请告诉我。
  • 我想合并 user_id 而不是索引
  • @Rahul 你应该在你的问题中提到这一点。无论如何,我已经更新了我的答案。
猜你喜欢
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 2018-01-15
  • 1970-01-01
  • 2012-08-25
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
相关资源
最近更新 更多