2017-09-25 52 views
-1

我開始學習lodash,無法理解如何將鍵移動到同一對象的另一個鍵。從API我得到下一個數據(用戶列表):如何通過lodash將某些鍵移動到另一個對象的鍵上?

[ 
{ 
    "id": 1, 
    "username": "test1", 
    "phone": null, 
    "email": "[email protected]", 
    "role": "admin", 
    "language": "en", 
    "created_at": "2016-12-16 14:25:23", 
    "updated_at": "2016-12-16 14:25:23" 
}, ... ] 

,我希望得到

[ 
{ 
    "hidden": { 
      "id": 1, 
      "username": "test1", 
      "language": "en", 
      "created_at": "2016-12-16 14:25:23", 
      "updated_at": "2016-12-16 14:25:23" 
    }, 
    "phone": null, 
    "email": "[email protected]", 
    "role": "admin" 
}, 
{ 
    "hidden": { 
      "id": 2, 
      "username": "test2", 
      "language": "en", 
      "created_at": "2017-09-22 10:45:00", 
      "updated_at": "2017-09-22 10:45:00" 
    }, 
    "phone": null, 
    "email": "[email protected]", 
    "role": "moderator" 
} 

]

回答

0

隨着lodash,您可以_.map()數組,並使用_.pick()_.omit(),和_.assign()來塑造新對象:

var data = [{ 
 
    "id": 1, 
 
    "username": "test1", 
 
    "phone": null, 
 
    "email": "[email protected]", 
 
    "role": "admin", 
 
    "language": "en", 
 
    "created_at": "2016-12-16 14:25:23", 
 
    "updated_at": "2016-12-16 14:25:23" 
 
}]; 
 

 
var baseKeys = ['phone', 'email', 'role']; 
 

 
var result = _.map(data, function(o) { 
 
    return _.assign(_.pick(o, baseKeys), { 
 
    hidden: _.omit(o, baseKeys) 
 
    }); 
 
}); 
 

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

另一種選擇是用ES6 Rest/Spread Properties(需要用巴別Object rest spread transform)。 Map該數組,然後使用解構和對象休息提取屬性。組裝使用shorthand property names新對象:

const data = [{ 
 
    "id": 1, 
 
    "username": "test1", 
 
    "phone": null, 
 
    "email": "[email protected]", 
 
    "role": "admin", 
 
    "language": "en", 
 
    "created_at": "2016-12-16 14:25:23", 
 
    "updated_at": "2016-12-16 14:25:23" 
 
}]; 
 

 
const result = data.map(({ phone, email, role, ...hidden }) => ({ 
 
    phone, 
 
    email, 
 
    role, 
 
    hidden 
 
})); 
 

 
console.log(result);

+0

welcome :)的確,ES6傾向於創建乾淨的代碼。但是請注意,對象休息/傳播不是ES6,而是一個提議,並且您需要使用轉換插件的babel。 –

0

你可以破壞的對象和重組的對象。

var data = [{ id: 1, username: "test1", phone: null, email: "[email protected]", role: "admin", language: "en", created_at: "2016-12-16 14:25:23", updated_at: "2016-12-16 14:25:23" }], 
 
    result = data.map(({ id, username, phone, email, role, language, created_at, updated_at }) => ({ 
 
     phone, 
 
     email, 
 
     role, 
 
     hidden: { id, username, language, created_at, updated_at } 
 
    })); 
 
    
 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

0
const newArray = _.map(array,(obj) => { 
    return { 
    hidden: _.pick(obj, ['id', 'username', 'language', 'created_at', 'updated_at']), 
    phone: obj.phone, 
    email: obj.email, 
    role: obj.role 
    } 
} 

你不能移動它們,但你可以_.pick()他們。

相關問題