Manipulating JavaScript Object

Photo by Klara Avsenik on Unsplash

In my last blog we were looking at object property flags and descriptors in JavaScript. In this blog, we will be looking at various ways of manipulating the Object.

Object.assign(target, ...sources)

It is useful for cloning an object:

const obj = { a: 1 };
const copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }

However, beware of deep clone.

For deep cloning, we need to use alternatives, because Object.assign() copies property values. If the value is a nested object, it only copies the reference value.

Object.create(proto, [propertiesObject])

oco = Object.create( {} );   

Object.entries(obj)/keys(obj)/values(obj)

const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.entries(obj));
// [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]

The Object.fromEntries() method transforms a list of key-value pairs into an object.

const map = new Map([ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]);
const obj = Object.fromEntries(map);
console.log(obj); // { 0: 'a', 1: 'b', 2: 'c' }

The Object.keys() method returns an array of a given object's own enumerable property names.

const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(arr)); // console: ['0', '1', '2']

The Object.values() method returns an array of a given object's own enumerable property values.

const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.values(arr)); // console: ['a', 'b', 'c']

Object.freeze(obj)

  • new properties from being added to it,
  • existing properties from being removed,
  • changing the enumerability, configurability, or writability of existing properties, and
  • the values of existing properties from being changed,
  • its prototype from being changed.

Note that similar to object.assign() , object.freeze() is a shallow operation. The result of calling Object.freeze(object) only applies to the immediate properties of object itself but not on nested object.

const employee = {
name: "Mayank",
address: {
street: "Rohini",
}
};
Object.freeze(employee);employee.name = "Dummy";
employee.address.city = "Noida";
console.log(employee.address.city) // "Noida"

Object.getOwnPropertyNames(obj)

var arr = ['a', 'b', 'c'];
console.log(Object.getOwnPropertyNames(arr)
// ["0", "1", "2", "length"]

Object.is(value1, value2);

Note that this is not the same as being equal according to the == operator. as == operator applies various coercions to both sides before testing for equality . This is also not the same as being equal according to the === operator. The === operator treats the number values -0 and +0 as equal and treats Number.NaN as not equal to NaN.

Object.is([], []);           // false
var foo = { a: 1 };
var bar = { a: 1 };
Object.is(foo, foo); // true
Object.is(foo, bar); // false
Object.is(null, null); // true

So that’s so much of it today!

Happy Reading!