JavaScript Object Methods

abidullah786

ABIDULLAH786

Posted on July 24, 2022

JavaScript Object Methods

Introduction

Every day we are working on real-world problems so if the implementation language is JavaScript then we must work with objects. And to work efficiently we must know the most used methods of the object. And I want to reference that information in this article is based on Mozila

Table Of Contents

  1. create()
  2. assign()
  3. keys()
  4. values()
  5. entries()
  6. fromEntries()
  7. freez() & seal()

Object.create()

The object.create() method Is used to create a new object and link I to the prototype of an existing object. It returns a new object with the specified prototype object and properties.

let student = {
    name: "Abid",
    age: 23,
    display() {
        console.log("Name: ", this.name);
        }
};

let std = Object.create(Student);  // Object Creation

std.name = "Ahmed" 
std.display();  // with same properties
Enter fullscreen mode Exit fullscreen mode

Object.assign ()

The Object.assign() method assigns/copies enumerable and own properties from a source object to a target object. It returns the modified or new target object.

const target = { a: 1, b: 2 };
const source = { c: 4, d: 5 };

// it merge the objects and return new objects
const newTarget = Object.assign(target, source); 

console.log(target);
// expected output: Object { a: 1, b: 2, c: 4, d:5 }

console.log(newTarget);
// expected output: Object { a: 1, b: 2, c: 4, d:5 }
Enter fullscreen mode Exit fullscreen mode

As you have noticed in above example that after merging two objects it returned the result in new object, but also it changed target object itself. If we do not want to reflect out changes on existing objects then we have to use empty {} object as a first parameter of assign method.

const target = { a: 1, b: 2 };
const source = { c: 4, d: 5 };

// it merge the objects and return new objects
const newObj = Object.assign({},target, source); 

console.log(target);
// expected output: Object { a: 1, b: 2 }

console.log(newObj);
// expected output: Object { a: 1, b: 2, , c: 4, d:5  }
Enter fullscreen mode Exit fullscreen mode

If the source and target property are the same then it overwrites the target property by the new value of source.

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const newObj = Object.assign({}, target, source);

console.log(target);
// expected output: Object { a: 1, b: 2}

console.log(newObj);
// expected output: Object { a: 1, b: 4, c: 5 } // the target property is overwrite by source
Enter fullscreen mode Exit fullscreen mode

Cloning an object

const obj = { a: 1 };
const copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
Enter fullscreen mode Exit fullscreen mode

Here the cloning has two different behaviors if the object has no inner object then the cloning work as deep clone and when the cloning object has any nested object the cloning work as shallow copy only for nested object, it will be more cleared with example:

let obj1 = { a: 0 , b: { c: 0}};
let obj2 = Object.assign({}, obj1);
console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}

obj1.b.c = 3; // it reflect the changes in every shallow copy
console.log(JSON.stringify(obj1)); // { "a": 0, "b": { "c": 3}}
console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 3}}
Enter fullscreen mode Exit fullscreen mode

In above example the obj1 has the inner object like this b: { c: 0} so this object's reference will be shared with all new clones and change in one place will cause in all places.

3. Object.keys():

Object.keys() create and return an array containing the keys/names of an object.

let student = {
    name: "Abid",
    age: 23,
    status: "Student"
};
console.log(Object.keys(Student)) // ['name', 'age', 'status']
console.log(Object.keys(Student))
Enter fullscreen mode Exit fullscreen mode

4. Object.values()

Object.values() create an array containing the values of an object.

let student = {
    name: "Abid",
    age: 23,
    status: "Student"
};
console.log(Object.values(Student)) //  ['Abid', 23, 'Student']
Enter fullscreen mode Exit fullscreen mode

5. Object.entries():

Object.entries() returns an array of the key/values pairs of an object.

let student = {
    name: "Abid",
    age: 23,
    status: "Student"
};
console.log(Object.entries(student)) // [ ["name", "Abid"], ["age", 23], ["status", "Student"]]
Enter fullscreen mode Exit fullscreen mode

6. Object.fromEntries()

Object.fromEntries() does the exact opposite of Object.entries(). It takes an array of key values pairs and convert them into single object.

let student = {
    name: "Abid",
    age: 23,
    status: "Student"
};
let studentArray = [["name", "Abid"], ["age", 23], ["status", "Student"]];
console.log(Object.fromEntries(studentArray)) // {name: 'Abid', age: 23, status: 'Student'}
Enter fullscreen mode Exit fullscreen mode

7. Object.freez() and Object.seal()

Common Points:

  • Both prevents a JavaScript object from being altered.
  • You can’t add new properties
  • You can’t remove existing properties.

Difference:
Object.seal() allows the modification of existing properties.

freez vs seal

Note: The compiler does not throw any error if we violate any of the above mentioned rule.

Code Level Example (freez and seal)

let frozen = Object.freeze({ username: "Abid"})
let sealed = Object.seal({ username: "Abid"})

// Adding new Property 
frozen.name = "Ahmed"
sealed.name = "Ahmed"

// removing existing property
delete frozen.username;
delete sealed.username;

// updating the existing property
frozen.username = "Ahmed"
sealed.username = "Ahmed"

console.log(frozen) // { username: 'Abid' }
console.log(sealed) // { username: 'Ahmed' }
Enter fullscreen mode Exit fullscreen mode

Important Points: (freez and seal)

  • Remember that both methods perform a shallow freeze/seal on the object.
  • This means that nested objects and arrays are not frozen or sealed and can be changed.
  • To prevent this, you need the concept of deep freezing of objects which I will be discussing in upcoming post

Buy-me-a-coffee


Exploring new concepts in #JavaScript and sharing with others is my passion and it gives me pleasure to help and inspire people. If you have any suggestion or want to add something please comment.

If you liked my work connect with me on Twitter, Linkedinand GitHub to stay updated and join the discussion!

💖 💪 🙅 🚩
abidullah786
ABIDULLAH786

Posted on July 24, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related