JavaScript Object and It’s Method

·

2 min read

A key type of data structure in JavaScript is the object. Data may be stored and arranged using objects as key-value pairs. In this post, we'll look at some of the most popular object methods in JavaScript as well as objects.

Making Things

Curly braces can be used in JavaScript to define key-value pairs for objects. Here's an illustration:

javascriptCopy codelet myObject = { 
  name: "John", 
  age: 30 
};

In this example, we're creating an object with two key-value pairs. The key name has a value of "John", and the key age has a value of 30.

Object Methods

JavaScript provides a wide variety of methods for working with objects. Here are some of the most commonly used methods:

Object.keys()

The Object.keys() method returns an array of all the keys in an object. Here's an example:

javascriptCopy codelet myObject = { 
  name: "John", 
  age: 30 
};
let keys = Object.keys(myObject);
console.log(keys); // ["name", "age"]

In this example, we're using Object.keys() to get an array of the keys in the myObject object.

Object.values()

The Object.values() method returns an array of all the values in an object. Here's an example:

javascriptCopy codelet myObject = { 
  name: "John", 
  age: 30 
};
let values = Object.values(myObject);
console.log(values); // ["John", 30]

In this example, we're using Object.values() to get an array of the values in the myObject object.

Object.entries()

The Object.entries() method returns an array of arrays, where each sub-array contains a key-value pair from the object. Here's an example:

javascriptCopy codelet myObject = { 
  name: "John", 
  age: 30 
};
let entries = Object.entries(myObject);
console.log(entries); // [["name", "John"], ["age", 30]]

In this example, we're using Object.entries() to get an array of arrays, where each sub-array contains a key-value pair from the myObject object.

Object.assign()

The Object.assign() method copies the values of all enumerable properties from one or more source objects to a target object. Here's an example:

javascriptCopy codelet target = { name: "John" };
let source = { age: 30 };
let mergedObject = Object.assign(target, source);
console.log(mergedObject); // {name: "John", age: 30}

In this example, we're using Object.assign() to merge the target object with the source object, and storing the result in a new object called mergedObject.

Conclusion

A robust data structure that lets you store and work with data as key-value pairs is the JavaScript object. You should now have a strong basis to start using objects and advance your programming abilities thanks to the object techniques presented in this tutorial.