如何使用lodash连接数组对象

时间:2018-02-09 06:35:35

标签: javascript arrays

我有两个不同数组对象的变量。一个是集合(this.collection)对象,第二个是用户(this.user)对象。

我想通过UID将这两个对象合并为一个。 这是collection object

   {  
       "id":"d67de5QJ",
       "admins":[  
          "494949393"
       ],
       "color":"#029ae4",
       "components":{  
          "forums":false,
          "pages":true,
          "photos":false,
          "videos":false
       },
       "createdAt":"2018-02-09 14:38:59",
       "description":"Angular is a TypeS",
       "homepage":"pages",
       "photoURL":"https://firebase..",
       "status":"Public",
       "title":"Angular 5",
       "uid":"hlyAbEUfJhbxy",
       "updatedAt":"2018-02-09 14:38:59"
    }

这是user object

{
  "bio": "<strong>PROFILE NEEDS EDITING",
  "contactInfo": {
    ...
  },
  "createdAt": "2018-02-09 12:43:47",
 ,
  "email": "email@gmail.com",
  "avatar": "https://lh5.googleusercontent.com/-3LjYEmTIZlo/A...",
  "roles": {
    "admin": false,
    "dealer": false,
    "user": true
  },
  "status": "online",
  "uid": "hlyAbEUfJhbxy",
  "updatedAt": "2018-02-09 14:37:23",
}

如何使用LoDash或vanilla JavaScript实现这一目标?如您所见,还有其他常见属性,例如 updatedAt createdAd

我尝试了这个但是我得到了一个空对象

if(this.collection) {
          this._auth.getUser(this.collection.uid).subscribe((user) => {
            this.user = user;
            const col = unionBy(this.user, this.collection, this.collection.uid)
             console.log(col)
          });

2 个答案:

答案 0 :(得分:0)

Object.assign()适用于此。 Here您可以找到详细解释。

请参阅小提琴here

var col =   {  
       "id":"d67de5QJ",
       "admins":[  
          "494949393"
       ],
       "color":"#029ae4",
       "components":{  
          "forums":false,
          "pages":true,
          "photos":false,
          "videos":false
       },
       "createdAt":"2018-02-09 14:38:59",
       "description":"Angular is a TypeS",
       "homepage":"pages",
       "photoURL":"https://firebase..",
       "status":"Public",
       "title":"Angular 5",
       "uid":"hlyAbEUfJhbxy",
       "updatedAt":"2018-02-09 14:38:59"
    }

 var user = {
  "bio": "<strong>PROFILE NEEDS EDITING",
  "createdAt": "2018-02-09 12:43:47",

  "email": "email@gmail.com",
  "avatar": "https://lh5.googleusercontent.com/-3LjYEmTIZlo/A...",
  "roles": {
    "admin": false,
    "dealer": false,
    "user": true
  },
  "status": "online",
  "uid": "hlyAbEUfJhbxy",
  "updatedAt": "2018-02-09 14:37:23",
}

console.log(Object.assign(col,user))

答案 1 :(得分:0)

您可以使用loadash merge:_.merge。与Object.assign不同,_.merge甚至可以处理嵌套对象。查找文档和示例here