Javascript Objects
ES6's Object.assign() function can be used to copy all of the enumerable properties from an existing Objecct instance to a new one.
const existing = { a: 1, b: 2, c: 3 };
const clone = Object.assign({}, existing);
This includes Symbol properties in addition to String ones.
Object rest/spread destructuring which is currently a stage 3 proposal provides an even simpler way to create shallow clones of Object instances:
const existing = { a: 1, b: 2, c: 3 };
const { ...clone } = existing;
If you need to support older versions of JavaScript, the most-compatible way to clone an Object is by manuallly iterating over its properties and filtering out inherited ones using .hasOwnProperty().
var existing = { a: 1, b: 2, c: 3 };
var clone = {};
for (var prop in existing) {
if (existing.hasOwnProperty(prop)) {
clone[prop] = existing[prop];
}
}
Object.freeze
Object.freeze makes an object immutable by preventing the addition of new properties, the removal of existing properties, and the modification of the enumerability, configurability, and writability of existing properties. It also prevents the value of existing properties from being changed. However, it does not work recursively which means that child objects are not automatically frozen and are subject to change.
The operations following the freeze will fail silently unless the code is running in strict mode. If the code is in strict mode, a TypeError will be thrown.
var obj = {
foo: 'foo',
bar: [1, 2, 3],
baz: {
foo: 'nested-foo'
}
};
Object.freeze(obj);
// Cannot add new properties
obj.newProperty = true;
// Cannot modify existing values or their descriptors
obj.foo = 'not foo';
Object.defineProperty(obj, 'foo', {
writable: true
});
// Cannot delete existing properties
delete obj.foo;
// Nested objects are not frozen
obj.bar.push(4);
obj.baz.foo = 'new foo';
Convert object's values to array
var obj = {
a: "hello",
b: "this is",
c: "javascript!",
};
You can convert its values to an array by doing:
var array = Object.keys(obj)
.map(function(key) {
return obj[key];
});
console.log(array);
Output
Object.getOwnPropertyDescriptor
Get the description of a specific property in an object
var sampleObject = {
hello: 'world'
};
Object.getOwnPropertyDescriptor(sampleObject, 'hello');
Output
Object.keys
Object.keys(obj) returns an array of a given object's keys.
var obj = {
a: "hello",
b: "this is",
c: "javascript!"
};
var keys = Object.keys(obj);
console.log(keys);
Output
Object.values()
The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.values(obj));