About
object in javascript
An object is a data type in Javascript.
An object follows a json data structure with key that holds property value. The value may be of a variable or a function
In JavaScript, a function is an object. As the scope in Javascript is function based, an object represents also a scope (see the this variable)
The object inheritance follows the prototypical model.
Example
With Function
A function is also an object and can be a property of an object.
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
// New family object
var family = {};
family.mother = new Person("Nico", "Gerard", 41);
family.father = new Person("Madelief", "Gerard", 9);
family.daughter = new Person("Melissa", "Gerard", 6);
family.son = new Person("Rixt", "Van Der Veen", 8);
Management
Initialization
en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer
Objects can be initialized using:
- new Object(), See JavaScript - new
- Object.create(), Create an object from a Javascript - (Prototype Model|Prototypical object).
- or using the literal notation. See below.
Constructor (new)
function myObject(arg){
this.prop1 = arg;
this.prop2 = arg + arg;
this.prop3 = arg.toUpperCase;
}
var obj1 = new myObject("foo");
console.log("An object obj1 was created with the following structure:");
console.log(obj1);
More, see Javascript - Object Constructor
Syntax / Literal Notation
A object with two fields (What is JSON (JavaScript Object Notation)?). All initializations are equivalent
- json notation
point = {x:3,y:2}
- Property Access pattern
point.x = 3
point.y = 2
- Other access pattern
point["x"] = 3
point["y"] = 2
An object in Javascript has the same syntax than the What is JSON (JavaScript Object Notation)? format. Curly brackets {} indicate then an object.
Example
var computer = {
os: "windows",
memoryGb: 4,
color: "blue", /* A property name must not begin with a number */
bit64: true
};
console.log(computer.os);
console.log(computer.memoryGb);
console.log(computer.color);
console.log(computer.bit64);
Key: Property
See:
type (instanceof)
To check the type of an object, you can use the instanceof operator
Type definition
With typescript.
How to define a general data object?
const properties: { [key: string]: any } = {};
// or
const properties: { [key: string]: object | object[] } = {};
Function Argument
For an object passed as a function argument For the function:
let myfunction = ({ name, age }){ ...}
- Inline: if the object is used a a function parameter
let myfunction = ({ name, age }: {name: string, age: number})
- Via an type definition
type Person {
name: string
age: number
}
let myfunction = ({ name, age }: Person)
Copy / Clone
Spread
Spread syntax.
As this is not implemented on all browsers, you may need to use a transpiler. The below code works with babel.
var user = { name: "Name" };
var userExtend = {...user, age: 44};
console.log(user);
console.log(userExtend);
Copy with Jquery Extend
var foo = { a: "a" };
console.log(foo.a);
console.log(foo.b);
// One time property copying
var bar = $.extend({}, foo);
bar.b = "b";
console.log(bar.a);
console.log(bar.b);
Immutability
Create
With delegation (Prototype)
prototype Delegation
var foo = { a: "a" };
// bar is a new object where foo is its prototype
var bar = Object.create(foo);
console.log("bar got the property of its prototype: "+bar.a);
if ("a" in bar) {
console.log("a is seen as a property of bar");
}
foo.b="b";
console.log("bar got also the new properties of its prototype: Example with b: "+bar.b);
if ("b" in bar) {
console.log("b is also seen as a property of bar");
}
Merge
Jquery Extend
- Default behavior: The value of the extended object is overwritten
obj1 = { color: "blue" };
obj2 = { color: "red", length: 10 };
jQuery.extend(obj1, obj2);
console.log(obj1);
- Getting a new object without modifying the passed object
obj1 = { color: "blue" };
obj2 = { color: "red", length: 10 };
obj3 = $.extend({}, obj1, obj2);
console.log("Obj1 value is ")
console.log(obj1);
console.log("Obj3 value is ");
console.log(obj3);
Xtend
https://www.npmjs.com/package/xtend - Node - Library
var extend = require("xtend")
// extend returns a new object. Does not mutate arguments
var combination = extend({
a: "a",
b: 'c'
}, {
b: "b"
})
// { a: "a", b: "b" }
Object.assign (ES6)
All objects get merged into the first object. See en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
obj1 = { color: "blue" };
obj2 = { color: "red", length: 10 };
obj3 = { name: "TheName" };
Object.assign(obj1, obj2, obj3);
console.log("Obj1 value is ")
console.log(obj1);
Merge with the spread operator
Merge with the spread operator
obj1 = { color: "blue" };
obj2 = { color: "red", length: 10 };
obj3 = { name: "TheName" };
console.log('With Spread');
console.log({...obj1, ...obj2, ...obj3});
Equality
How to check the equality of 2 values in Javascript? (If they are the same)
Serialization / Deserialization
Language - Serialization/Deserialization (Data Storage Structure) - Encoding/Decoding - Codec
Example from object to string to object:
- Creating an object
class Color {
name;
constructor(name){
this.name = name;
}
getName(){
return this.name;
}
}
var blue = new Color("blue");
- Serialization
blueString = JSON.stringify(blue);
console.log(blueString);
- Deserialization (To modify a string in another type (such as date), you would use a third function as a parameter called a reviver).
var obj = JSON.parse(blueString);
var blueObj = Object.assign(new Color(), obj);
console.log("I have a beautiful "+blueObj.getName()+" color");
Serialization and deserialization of object are used to:
- store object as string
- but also to pass them between process. (Example: Puppeteer - How to pass back and forth a date (or a complex type) to the headless browser via the evaluate function)
Schema
Loop
For loop
You can loop over the property key.
Example:
var person = {name: "foo", length: 180};
for (let prop in person) {
console.log(prop + " : " + person[prop]);
}
More example on the page: Javascript - For Statement
Foreach loop
const person = {name: "foo", length: 180};
Object.keys(person ).map((key) => {
console.log(key+ " : " + person[key]);
});
More example on the page: Javascript - foreach instruction