We have already seen how to create objects and object methods, but there are built-in methods that JavaScript makes available for use.
Below are examples of a few methods:
const person = {
name: 'Bob',
age: 54,
country: 'London'
};
const toArray = Object.values(person);
console.log(toArray); // [ 'Bob', 54, 'London' ]
const person = {
name: 'Bello',
age: 27,
country: 'Nigeria'
};
const toStr = JSON.stringify(person);
console.log(toStr);
// {"name":"Bello","age":54,"country":"Nigeria"}
toStr[0]; // '{'
toStr[1]; // "
toStr[2]; // n
JSON.stringify
will not stringify functions:
const person = {
name: 'Bello',
age: function() {
return 27;
},
country: 'Nigeria'
};
const toStr = JSON.stringify(person);
console.log(toStr);
// {"name":"Bello","country":"Nigeria"}
We have to convert the function to string (toString
) first.
const person = {
name: 'Bello',
age: function() {
return 27;
},
country: 'Nigeria'
};
const str = person.age.toString();
console.log(str);
/*
function() {
return 27;
}
*/
const toStr = JSON.stringify(person);
console.log(toStr);
/*
function() {
return 27;
}
{"name":"Bello","country":"Nigeria"}
*/
Both arrays and objects are non-primitive data types as objects. Therefore a few object methods can work on arrays also. Like
JSON.stringify()
const arr = [ 'Bello', 27, 'Nigeria' ];
const toStr = JSON.stringify(arr);
console.log(toStr); // ["Bello",27,"Nigeria"]
toStr[0]; // "["
toStr[2]; // "B"
More on arrays later.
const person = {
name: 'Bob',
age: 54,
country: 'London'
};
const hasProp = person.hasOwnProperty('name');
hasProp; //true
Object.assign()
copies all objects properties into a new object
const obj1 = {
a: 1,
b: 2,
c: 3
};
const obj2 = {
d: 4,
e: 5
}
const newObj = Object.assign(obj1, obj2);
newObj; // { a: 1, b: 2, c: 3, d: 4, e: 5 }
The general syntax is:
newObj = Object.assign(obj1[, obj2, ...,objN]);
A similar new object property name overrides the old object property name.
Object.assign(oldObj, newObj)
const obj1 = {
a: 1,
b: 2,
c: 3
};
const obj2 = {
c: 100,
e: 5
}
const newObj = Object.assign(obj1, obj2);
newObj; // { a: 1, b: 2, c: 100, e: 5 }
c: 100
overridesc: 3
const person = {
name: 'Bob',
age: 54,
country: 'London'
};
const objKeys = Object.keys(person);
console.log(objKeys); // [ 'name', 'age', 'country' ]
The entries
method used on an object converts the object, property keys, and property values to an array.
Syntax:
[ [key1, value1], [key2, value2], ...[keyN], [valueN] ]
const person = {
name: 'Bob',
age: 54,
country: 'London'
};
const objEntries = Object.entries(person);
console.log(objEntries);
// [ [ 'name', 'Bob' ], [ 'age', 54 ], [ 'country', 'London' ] ]
objEntries[1]; // [ 'age', 54 ]
objEntries[1][0]; // "age"
All built-in static object methods can be found on MDN.
Happy coding!!!
Top comments (0)