Javascript - Object

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:

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

point = {x:3,y:2}
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 object?

let properties: { [key: string]: any } = {};

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})
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

https://facebook.github.io/react/docs/update.html

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

Jquery

  • 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:

Schema

See Javascript Object - 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

Documentation / Reference





Discover More
Data System Architecture
Collection - Map (Associative arrays|Dictionary)

A map is an object that maps keys to values (known as property) Also known as: associative memories” or “associative arrays” dictionary hash table A map cannot contain duplicate keys; each...
DOM - NodeList (Collection)

A nodelist is the result of a selection that returns more than one node (Generally an element) Nodelist: HTMLAllCollection, HTMLFormControlsCollection, HTMLOptionsCollection, interfaces are...
How to check the equality of 2 values in Javascript? (If they are the same)

This page discusses Equality between 2 Javascript values. Because every value in javascript is an object, it applies also to the object. Object.is verifies the value. in case of the primitive,...
How to create a javascript global library (namespace pattern)

This article show you how Javascript global library are created with the namespace pattern
Color Autocompletion List
How to create an Autocompletion functionality with CSS, Javascript and HTML

This article shows you how to create a search box with an autocompletion feature
JSON - ObjectId

ObjectId are generated identifier (known as surrogate) with the intent to be unique for a Json. ObjectId are custom UUID that are created from: a counter timestamp (milliseconds) node id (IP...
Javascript - Object Constructor

in Javascript of an object Invoking a function with the new operator treats it as a constructor. Unlike function calls and method calls, a constructor call passes a brand-new object as the value of this,...
Javascript Console Dir
Javascript - (Console) Logging

logging in javascript are functions of the console Console logging permits inspecting a Web application (page). window Level Shows All Shows all console output Errors Only show output from...
Javascript - (Object) Key

Object key management. A key is also known as a property name :) Check all properties (also the inherited one) check only the direct properties of the object and not the inherited one...
Javascript - (Object) Property

Property Management of an object A property has : a key and a value Property names can be Reference/Operators/Object_initializerdynamic Reference/Operators/delete A property may be...



Share this page:
Follow us:
Task Runner