Copy some properties from an object in javascript
For example, this is an account object.
const account = { login: "dancingbear", id: 123456, type: "Organization", site_admin: false, name: "dancingbear", blog: "https://opensource.dancingbear/", email: "dancingbear@example.com", bio: "dancingbear ❤️ Open Source", public_repos: 999, created_at: "2001-01-01T01:30:18Z", updated_at: "2020-02-16T21:09:14Z" };
To make a copy of the above account object with only some properties. In this case, it copies “name”, “email”, “bio”, and “created_at” from the original account object, the new object contains only these properties and values from the original account object.
function copySomeProperties(account) { return Object.keys(account).reduce(function(obj, k) { if (["name", "email", "bio", "created_at"].includes(k)) { obj[k] = account[k]; } return obj; }, {}); } const copiedAccountWithSomeProperties = copySomeProperties(account); console.log(JSON.stringify(copiedAccountWithSomeProperties));
The copied account object with some properties from the original account object.
{ "name": "dancingbear", "email": "dancingbear@example.com", "bio": "dancingbear ❤️ Open Source", "created_at": "2001-01-01T01:30:18Z" }
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts