Categories
JavaScript

The Ultimate Guide to Manipulating Objects in JavaScript

Spread the love

Define New Object Literal

You can define object literals in JavaScript. An object does not have to an instance of a class in JavaScript.

You can define it like this:

const obj = { chicken: { hasWings: true }}

Define Object with Constructor

JavaScript lets you define objects that can be instantiated like a class with the new keyword.

You can define it like this:

const bird = function(hasWings){  this.hasWings = hasWings;}const chicken = new bird(true);  
console.log(chicken.hasWings); // true

Note the use of the function keyword instead of an arrow function. It is required to set this’s scope to the function itself.

Since ES6, you can define an object as an instance of a class.

For example:

class bird{  
  constructor(hasWings){  
    this.hasWings = hasWings;  
  }  
}const chicken = new bird(true);  
console.log(chicken.hasWings); // true

Get Keys of Object

Object.keys can be used to get all the top level keys of an object as strings. For example:

const chicken = { hasWings: true, bodyParts: [ {head: 1} ]};  
console.log(Object.keys(chicken)) // ['hasWings', 'bodyParts'];

Get Entries of an Object

Object.entriescan be used to get all the top level keys value entries of an object as arrays. For example:

const chicken = { hasWings: true, bodyParts: ['head', 'tail']};  
console.log(Object.entries(chicken)) // [['hasWings', true], ['bodyParts', ['head', 'tail']]];

Merge Two Objects

We can use the spread operation to combine two objects into one.

const a = {foo: 1};  
const b = {bar: 1};  
const c = {...a, ...b}; // {foo: 1, bar: 1}

If two objects have the same keys, the value of the one that is merged in last will override the earlier one.

const a = {foo: 1};  
const b = {bar: 1};  
const c = {bar: 2};  
const d = {...a, ...b, ...c};   
console.log(d) // {foo: 1, bar: 2}

Prevent Modification to an Existing Object

Object.freeze can be used to prevent an object from being modified. freeze takes an object as its argument and freezes an object in place.

For example:

let a = {foo: 1};  
a.foo = 2;  
Object.freeze(a);  
a.foo = 3;  
console.log(a) // {foo: 2}

Check If an Object Can Be Modified

Object.isFrozen can be used to check if an object is frozen by Object.freeze .

For example:

let a = {foo: 1};  
a.foo = 2;  
Object.freeze(a);  
a.foo = 3;  
console.log(Object.isFrozen(a)) // true

Clone Objects

If you assign an object to another variable, it just assigns the reference to the original object, so both variables will point to the original object. When one of the variables are manipulated, both will be updated. This is not always the desired behavior. To avoid this, you need to copy an object from one variable to another.

In JavaScript, this is easy to do. To shallow copy an object, we can use Objec.assign(), which is built into the latest versions of JavaScript. This function does a shallow copy, which means it only copies the top level of an object, while the deeper levels remain linked to the original object reference. This may not be desired if there is nested in your original object.

Here is an example of how to use Object.assign :

const a = { foo: {bar: 1 }}  
const b = Object.assign({}, a) // get a clone of a which you can change with out modifying a itself

You can also clone an array like this:

const a = [1,2,3]  
const b = Object.assign([], a) // get a clone of a which you can change with out modifying a itself

To do a deep copy of a object without a library, you can JSON.stringify then JSON.parse :

const a = { foo: {bar: 1, {baz: 2}}  
const b = JSON.parse(JSON.strinfy(a)) // get a clone of a which you can change with out modifying a itself

This does a deep copy of an object, which means all levels of an object are cloned instead of referencing the original object.

JSON.parse and JSON.stringify only works with plain objects, which means it cannot have functions and other code that runs.

With ES6, you can also use object destructuring to shallow clone objects, like so:

const a = { foo: {bar: 1}}  
const b = {...a} // get a clone of a which you can change with out modifying a itself

Object.keys

Object.keys gets the top level list of keys of an object and returns an array of them. For example:

const a = {foo: 1, bar: 2};  
const length = Object.keys(a).length // 2

Object.getPropertyNames

Object.getPropertyNames also gets a list of all top level of keys of an object and return them as an array. For example:

const a = {foo: 1, bar: 2};  
const length = Object.getOwnPropertyNames(a).length // 2

for…in Loop

There is a special loop for looping through the keys of an object. You can do the following:

const a = {foo: 1, bar: 2};  
let keysCount = 0;  
for (let key in a) {  
    keysCount++;  
}  
console.log(keysCount) // 2

hasOwnProperty

You can check if an object has a property by calling hasOwnProperty of an object. For example:

const a = {foo: 1, bar: 2};  
a.hasOwnProperty(key); // true

That’s it — a few simple steps for a few simple operations!

Leave a Reply

Your email address will not be published. Required fields are marked *