使用下划线合并 JavaScript 中的数组对象?

Rah*_*hul -4 javascript arrays node.js underscore.js angular

I have two arrays and i want to combine them to get common result. array should be combine on the basis of user_id not on index How would i do this?

Array 1:

var array1 = [{
  "name": "Smart Test Pool",
  "user_id": 1,
  "total_time": "15.0",
}];
Run Code Online (Sandbox Code Playgroud)

Array 2:

var array2 = [{
  "user_id": 1,
  "total_hours_worked_milliseconds": 60060000,
  "total_time_unshedule_milliseconds": 540000
}];
Run Code Online (Sandbox Code Playgroud)

Result :

var result = [{
  "name": "Smart Test Pool",
  "user_id": 1,
  "total_time": "15.0",
  "total_hours_worked_milliseconds": 60060000,
  "total_time_unshedule_milliseconds": 540000
}]; 
Run Code Online (Sandbox Code Playgroud)

Moh*_*man 5

You can merge objects using:

1- Plain JS Methods:

You can use .map(), .find() and Object.assign():

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

Or spread syntax:

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

Demo:

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

2- Underscore

You can use .map() and .extend() methods:

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

Demo:

let result = array1.map((o, i) => (
  {...o,...array2.find(o2 => o2["user_id"] === o["user_id"])}
));
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)

Docs: