簡體   English   中英

如何使用 lodash 連接數組對象

[英]How to join array objects with lodash

我有兩個帶有兩個不同數組對象的變量。 一個是collection(this.collection)對象,第二個是user(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 實現這一點? 正如你所看到的,也有像updatedAtcreatedAd其他公共屬性。

我試過這個,但我得到一個空對象

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

Object.assign() 可以解決這個問題。 在這里你可以找到詳細的解釋。

在這里看到小提琴

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

您可以使用 loadash 合並: _.merge Object.assign不同, _.merge . _.merge甚至可以處理嵌套對象。 此處查找文檔和示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM