Some programmers find it hard to handle objects in javascript. So I made a pseudo-tutorial about tips and tricks for object handling.
Object making
First, Object making in javascript is easy and simple.
Static object making
The static object creation is described as follows:
const object = {
key_1: "value_1",
key_2: "value_2",
};
Dynamic object making
But, Some programmers prefer to use this dynamic object creation to avoid writing curly braces:
const object = {};
object.key_1 = "value_1";
object.key_2 = "value_2";
Object manipulation in javascript
In javascript, we can manipulate objects in any possible way, let's suppose I want to display in the console the keys of a certain object separately in an array data structure. we can use the Object.keys(myObject)
function and it will output an array with the object keys.
Here is an example:
const myObject = {
name: "John",
age: 30,
city: "New York"
};
const keys = Object.keys(myObject);
console.log(keys); // logs ["name", "age", "city"]
Also, object values in javascript can be separately shown in the console using the Object.values(myObject)
function.
const myObject = {
name: "John",
age: 30,
city: "New York"
};
const values = Object.values(myObject);
console.log(values); // logs ["John", 30, "New York"]
Now let's say we want to obtain both the values and the keys in the console but in a different data structure, and this can be done thanks to a function called Object.entries(myObject)
:
const entries = Object.entries(myObject);
console.log(entries); // logs [["name", "John"], ["age", 30], ["city", "New York"]]