Let's use them for some real-world scenarios + some ES6. (let's try some ARMD on the below object keys)

Wondering what is ARMD its Add, Read, Modify, Delete, its cool to coin your own jargon 😄

We will use users it as an array for further examples.

1. ARMD — Adding a new element to users



id: 4,

name: "Denomer Crazy",

username: "crazy.1",

email: "

phone: "",

website: "crazy.app",

password: "crazed_checker"

}; const newUser = {id: 4,name: "Denomer Crazy",username: "crazy.1",email: " deno@crazy.com ",phone: "",website: "crazy.app",password: "crazed_checker"}; const newData = [...users, newUser]; // add element at last

or

const newData = [newUser, ...users]; // add element at first

or

const newData = users.concat(newUser) // the old way

The use of ES6 spread operator makes it super easy to add elements to an array. We can use the spread operator to concat two different arrays, modify the shape of objects, or add dynamic key-value pairs, etc.

const hobbies = ['chess', 'pool'];

const newUsers = users.map(u => ({...u, hobbies}))

// this will add hobbies to users array and return newUsers array

2. ARMD — Get the email address, phone number, and website of users into new array

const contactInfo = users.map(({email, website, phone}) => ({email, website, phone}));

The use of ES6 of destructuring of object keys and map to get the contact info array for the user.

3. ARMD — Find and replace the value for the 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. ARMD —Delete some key’s from the object

Note: We will actually not delete the key but return a new object, if you want to delete the key use delete operator, here we are considering object immutability.

To delete keys there are a lot of ways but we will look at the easiest, single lined. Let's try to delete the website from users.

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

The 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, {}));