// simple and most popular way to create object
const person = {
name: 'Deepa'
};
You can also use new keyword
const person1 = new Object();
person1.name = 'Deepa';
console.log(person1); // {name: 'Deepa'}
You can also use 'new' with user defined constructor function.
E.g.
function person(name) {
this.name = name;
}
// Now anytime you want person object.
const personOne = new person('deepa');
const personTwo = new person('partha');
console.log(personOne); // {name: 'deepa'}
console.log(personTwo); // {name: 'partha'}
The Object.create() methods creates a new object, using an existing object as prototype of the newly created object.
It contains two parameter:
- First parameter is mandatory that serves prototype of new object to be created.
- Second is optional, it contains properties to be added to new object.
E.g.
const orgObject = { company: 'ABC' };
const employee = Object.create(orgObject, { name: { value: 'EmpOne'}});
console.log(employee); // {name: 'EmpOne'}
console.log(employee.name); // EmpOne
The Obeject.assign() method is used to copy all enumerable own properties value from one or more source objects to target object. It will return target object.
E.g.
const orgObject = { company: 'ABC' };
const carObject = { carName: 'Corola' };
const employee = Object.assign({}, orgObject, carObject);
// Now you can get employee object that has company and carName as its property.
console.log(employee); // {company: 'ABC', carName: 'Corola'}
This method defines new or modify existing property on object.
const object1 = {};
Object.defineProperties (object1, {
property1: {
value: 42
}
});
console.log(object1.property1); // 42
Similarly, we also have Object.defineProperty()
It returns an array of object's key value pairs.
The order of array is same as provided by a for in loop
const object1 = {
a: 'something',
b: 'nothing'
};
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
/* Output:
a: something
b: nothing
*/
It freezes an object. No longes can be changed.
E.g.
const obj = {
prop: 42
};
Object.freeze(obj);
obj.prop = 43;
console.log(obj.prop); // 42
// It can no longes be change due to freeze
It transforms a list of key-value pairs into an object.
E.g.
const entries = new Map([
[ 'foo', 'bar' ],
[ 'baz', 42 ]
]);
const obj = Object.fromEntries(entries);
console.log(obj); // {foo: 'bar', baz: 42}