Last active
October 7, 2019 03:12
-
-
Save secretgspot/ac166050da483fb1ddc82b19fd29e8e6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
.__..__ . ..__ | |
[__][__)|\/|| \ | |
| || \| ||__/ | |
ARMD its Add, Read, Modify, Delete | |
*/ | |
const users = [ | |
{ | |
id: 1, | |
name: "Jonathon Haley", | |
username: "Monte.Weber2", | |
email: "[email protected]", | |
}, | |
{ | |
id: 2, | |
name: "Dean John", | |
username: "dd.1", | |
email: "[email protected]", | |
} | |
]; | |
// 1. ADD — Adding a new element to users | |
const newUser = { | |
id: 4, | |
name: "Denomer Crazy", | |
username: "crazy.1", | |
email: "[email protected]", | |
}; | |
const newData = [...users, newUser]; // add element at last | |
const newData = [newUser, ...users]; // add element at first | |
const newData = users.concat(newUser) // the old way | |
// Extra! this will add hobbies to users array and return newUsers array | |
const hobbies = ['chess', 'pool']; | |
const newUsers = users.map(u => ({...u, hobbies})); | |
// 2. READ — Get email address, phone number and website of users into new array | |
const contactInfo = users.map(({email, website, phone}) => ({email, website, phone})); | |
// 3. MODIFY — Find and replace value for key of objects | |
const newUsers = users.map(u => u.id == 2? ({...u, name: 'te'}): u); | |
// this will return newUsers with all user having name 'te' | |
// 4. DELETE — Delete some key’s from object | |
const newUsers = users.map({id, email, name, username, phone, password} => ({id, email, username, email, phone, password})); | |
// will return an array with all keys other than website | |
// Above code seems to be practically difficult to code for big objects. | |
const newUsers = users.map(u => Object.keys(u).reduce((newObj, key) => key != 'website' ? { ...newObj, [key]: u[key]} : newObj, {})); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment