Destructuring assignment to costruct a new object - Is it possible? [duplicate] - javascript

This question already has answers here:
Is it possible to destructure an object and generate a new object in a single statement? [duplicate]
(2 answers)
How to get a subset of a javascript object's properties
(36 answers)
One-liner to take some properties from object in ES 6
(12 answers)
Closed 5 years ago.
Is it possible to use destructuring assignment syntax to make it possible to extract data objects into another object instead distinct variables?
Example which produce distinct variables (foo, bar):
var {p: foo, q: bar} = {p: 42, q: true};
console.log(foo); // 42
console.log(bar); // true
I would need in stead to create a new object which contains the following properties as:
var n = {
foo: 42,
bar: true
}

It is not possible. The term destructuring implies that object is destructured to variables.
A way to not pollute the scope with temporary variables is to use IIFE for destructuring:
obj = (({ foo = 'foo', bar = 'bar' }) => ({ foo, bar }))(obj);
This will assign default values and will pick only valid keys from the object.
If picking is not necessary, the cleanest recipe to do this with native JS features is ES6 Object.assign:
obj = Object.assign({ foo: 'foo', bar: 'bar' }, obj);
Or ES2018 spread:
obj = { foo: 'foo', bar: 'bar', ...obj};

It sort of is, but you'll need two steps. You can't destructure directly from an object into another object, but you can make this elegant by using ES6 object notation and wrapping it into a function.
function transformObject(object) {
const { p: foo, q: bar } = object;
const newObject = {
foo,
bar
};
return newObject;
}

You cannot do it using destructuring, but you could use a helper function like this:
function retag(newStructure, source) {
var result = {};
for (var key in newStructure) {
result[key] = source[newStructure[key]];
}
return result;
}
console.log(retag(
{ foo: 'a', bar: 'b' },
{ a: false, b: 42, c: 'unused'}
));

Related

Is there a way to capture a variable access? [duplicate]

Is there a way to set the default attribute of a Javascript object such that:
let emptyObj = {};
// do some magic
emptyObj.nonExistingAttribute // => defaultValue
Since I asked the question several years ago things have progressed nicely.
Proxies are part of ES6. The following example works in Chrome, Firefox, Safari and Edge:
let handler = {
get: function(target, name) {
return target.hasOwnProperty(name) ? target[name] : 42;
}
};
let emptyObj = {};
let p = new Proxy(emptyObj, handler);
p.answerToTheUltimateQuestionOfLife; //=> 42
Read more in Mozilla's documentation on Proxies.
Use destructuring (new in ES6)
There is great documentation by Mozila as well as a fantastic blog post that explains the syntax better than I can.
To Answer Your Question
var emptyObj = {};
const { nonExistingAttribute = defaultValue } = emptyObj;
console.log(nonExistingAttribute); // defaultValue
Going Further
Can I rename this variable? Sure!
const { nonExistingAttribute: coolerName = 15} = emptyObj;
console.log(coolerName); // 15
What about nested data? Bring it on!
var nestedData = {
name: 'Awesome Programmer',
languages: [
{
name: 'javascript',
proficiency: 4,
}
],
country: 'Canada',
};
var {name: realName, languages: [{name: languageName}]} = nestedData ;
console.log(realName); // Awesome Programmer
console.log(languageName); // javascript
There isn't a way to set this in Javascript - returning undefined for non-existent properties is a part of the core Javascript spec. See the discussion for this similar question. As I suggested there, one approach (though I can't really recommend it) would be to define a global getProperty function:
function getProperty(o, prop) {
if (o[prop] !== undefined) return o[prop];
else return "my default";
}
var o = {
foo: 1
};
getProperty(o, 'foo'); // 1
getProperty(o, 'bar'); // "my default"
But this would lead to a bunch of non-standard code that would be difficult for others to read, and it might have unintended consequences in areas where you'd expect or want an undefined value. Better to just check as you go:
var someVar = o.someVar || "my default";
my code is:
function(s){
s = {
top: s.top || 100, // default value or s.top
left: s.left || 300, // default value or s.left
}
alert(s.top)
}
The way I achieve this is with the object.assign function
const defaultProperties = { 'foo': 'bar', 'bar': 'foo' };
const overwriteProperties = { 'foo': 'foo' };
const newObj = Object.assign({}, defaultProperties, overwriteProperties);
console.log(defaultProperties); // {"foo": "bar", "bar": "foo"}
console.log(overwriteProperties); // { "foo": "foo" };
console.log(newObj); // { "foo": "foo", "bar": "foo" }
This seems to me the most simple and readable way of doing so:
let options = {name:"James"}
const default_options = {name:"John", surname:"Doe"}
options = Object.assign({}, default_options, options)
Object.assign() reference
This sure sounds like the typical use of protoype-based objects:
// define a new type of object
var foo = function() {};
// define a default attribute and value that all objects of this type will have
foo.prototype.attribute1 = "defaultValue1";
// create a new object of my type
var emptyObj = new foo();
console.log(emptyObj.attribute1); // outputs defaultValue1
I think the simplest approach is using Object.assign.
If you have this Class:
class MyHelper {
constructor(options) {
this.options = Object.assign({
name: "John",
surname: "Doe",
birthDate: "1980-08-08"
}, options);
}
}
You can use it like this:
let helper = new MyHelper({ name: "Mark" });
console.log(helper.options.surname); // this will output "Doe"
Documentation (with polyfill):
https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Or you can try this
dict = {
'somekey': 'somevalue'
};
val = dict['anotherkey'] || 'anotherval';
Simplest of all Solutions:
dict = {'first': 1,
'second': 2,
'third': 3}
Now,
dict['last'] || 'Excluded'
will return 'Excluded', which is the default value.
If you only have an object that is a single level deep (nested object properties will not merge as expected since it directly destructures from the first level), you can use the following destructuring syntax:
const options = {
somevar: 1234,
admin: true
};
const defaults = {
test: false,
admin: false,
};
var mergedOptions = {...defaults, ...options};
Of which the output would be:
console.log(options);
// { somevar: 1234, admin: true }
console.log(mergedOptions);
// { test: false, admin: true, somevar: 1234 }
Or even formatted as a single statement (this is slightly unreadable though):
const options = {...{
// Defaults
test: false,
admin: false,
}, ...{
// Overrides
somevar: 1234,
admin: true
}};
I saw an article yesterday that mentions an Object.__noSuchMethod__ property: JavascriptTips I've not had a chance to play around with it, so I don't know about browser support, but maybe you could use that in some way?
I'm surprised nobody has mentioned ternary operator yet.
var emptyObj = {a:'123', b:'234', c:0};
var defaultValue = 'defaultValue';
var attr = 'someNonExistAttribute';
emptyObj.hasOwnProperty(attr) ? emptyObj[attr] : defaultValue;//=> 'defaultValue'
attr = 'c'; // => 'c'
emptyObj.hasOwnProperty(attr) ? emptyObj[attr] : defaultValue; // => 0
In this way, even if the value of 'c' is 0, it will still get the correct value.
var obj = {
a: 2,
b: 4
};
console.log(obj);
--> {a: 2, b: 4}
function applyDefaults(obj) {
obj.a ||= 10;
obj.b ||= 10;
obj.c ||= 10;
}
// do some magic
applyDefaults(obj);
console.log(obj);
--> {a: 2, b: 4, c: 10}
This works because
undefined || "1111111" --> "1111111"
"0000000" || "1111111" --> "0000000"
as null, undefined, NaN, 0, "" (Empty String), false itself, are all considered to be equivalent to false (falsy). Anything else is true (truthy).
Note that this is not uniformly supported across browsers and nodejs versions (confirm for yourself).
So two troublesome cases are the empty String "" and 0 (zero). If it is important not to override those, you might need to rewrite this as:
if (typeof obj.d == "undefined") obj.d = "default"
This will be better supported across browsers also.
Alternatively you could write this as:
obj.d ??= "default"
This is the nullish assignment which applies only to values that are null or undefined (nullish) - of which the empty string is not part. However, this has again a diminished cross-browser support.
See also on the official Mozilla Website - Assigning a default value to a variable.
This is actually possible to do with Object.create. It will not work for "non defined" properties. But for the ones that has been given a default value.
var defaults = {
a: 'test1',
b: 'test2'
};
Then when you create your properties object you do it with Object.create
properties = Object.create(defaults);
Now you will have two object where the first object is empty, but the prototype points to the defaults object. To test:
console.log('Unchanged', properties);
properties.a = 'updated';
console.log('Updated', properties);
console.log('Defaults', Object.getPrototypeOf(properties));
Object.withDefault = (defaultValue,o={}) => {
return new Proxy(o, {
get: (o, k) => (k in o) ? o[k] : defaultValue
});
}
o = Object.withDefault(42);
o.x //=> 42
o.x = 10
o.x //=> 10
o.xx //=> 42
One approach would be to take a defaults object and merge it with the target object. The target object would override values in the defaults object.
jQuery has the .extend() method that does this. jQuery is not needed however as there are vanilla JS implementations such as can be found here:
http://gomakethings.com/vanilla-javascript-version-of-jquery-extend/
With the addition of the Logical nullish assignment operator, you can now do something like this
const obj = {}
obj.a ??= "default";
In the case where you have an empty list as the default value and want to push to it, you could do
const obj = {}
(obj.a ??= []).push("some value")
I came here looking for a solution because the header matched my problem description but it isn't what i was looking for but i got a solution to my problem(I wanted to have a default value for an attribute which would be dynamic something like date).
let Blog = {
title : String,
image : String,
body : String,
created: {type: Date, default: Date.now}
}
The above code was the solution for which i finally settled.

Default property on Javascript object [duplicate]

Is there a way to set the default attribute of a Javascript object such that:
let emptyObj = {};
// do some magic
emptyObj.nonExistingAttribute // => defaultValue
Since I asked the question several years ago things have progressed nicely.
Proxies are part of ES6. The following example works in Chrome, Firefox, Safari and Edge:
let handler = {
get: function(target, name) {
return target.hasOwnProperty(name) ? target[name] : 42;
}
};
let emptyObj = {};
let p = new Proxy(emptyObj, handler);
p.answerToTheUltimateQuestionOfLife; //=> 42
Read more in Mozilla's documentation on Proxies.
Use destructuring (new in ES6)
There is great documentation by Mozila as well as a fantastic blog post that explains the syntax better than I can.
To Answer Your Question
var emptyObj = {};
const { nonExistingAttribute = defaultValue } = emptyObj;
console.log(nonExistingAttribute); // defaultValue
Going Further
Can I rename this variable? Sure!
const { nonExistingAttribute: coolerName = 15} = emptyObj;
console.log(coolerName); // 15
What about nested data? Bring it on!
var nestedData = {
name: 'Awesome Programmer',
languages: [
{
name: 'javascript',
proficiency: 4,
}
],
country: 'Canada',
};
var {name: realName, languages: [{name: languageName}]} = nestedData ;
console.log(realName); // Awesome Programmer
console.log(languageName); // javascript
There isn't a way to set this in Javascript - returning undefined for non-existent properties is a part of the core Javascript spec. See the discussion for this similar question. As I suggested there, one approach (though I can't really recommend it) would be to define a global getProperty function:
function getProperty(o, prop) {
if (o[prop] !== undefined) return o[prop];
else return "my default";
}
var o = {
foo: 1
};
getProperty(o, 'foo'); // 1
getProperty(o, 'bar'); // "my default"
But this would lead to a bunch of non-standard code that would be difficult for others to read, and it might have unintended consequences in areas where you'd expect or want an undefined value. Better to just check as you go:
var someVar = o.someVar || "my default";
my code is:
function(s){
s = {
top: s.top || 100, // default value or s.top
left: s.left || 300, // default value or s.left
}
alert(s.top)
}
The way I achieve this is with the object.assign function
const defaultProperties = { 'foo': 'bar', 'bar': 'foo' };
const overwriteProperties = { 'foo': 'foo' };
const newObj = Object.assign({}, defaultProperties, overwriteProperties);
console.log(defaultProperties); // {"foo": "bar", "bar": "foo"}
console.log(overwriteProperties); // { "foo": "foo" };
console.log(newObj); // { "foo": "foo", "bar": "foo" }
This seems to me the most simple and readable way of doing so:
let options = {name:"James"}
const default_options = {name:"John", surname:"Doe"}
options = Object.assign({}, default_options, options)
Object.assign() reference
This sure sounds like the typical use of protoype-based objects:
// define a new type of object
var foo = function() {};
// define a default attribute and value that all objects of this type will have
foo.prototype.attribute1 = "defaultValue1";
// create a new object of my type
var emptyObj = new foo();
console.log(emptyObj.attribute1); // outputs defaultValue1
I think the simplest approach is using Object.assign.
If you have this Class:
class MyHelper {
constructor(options) {
this.options = Object.assign({
name: "John",
surname: "Doe",
birthDate: "1980-08-08"
}, options);
}
}
You can use it like this:
let helper = new MyHelper({ name: "Mark" });
console.log(helper.options.surname); // this will output "Doe"
Documentation (with polyfill):
https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Or you can try this
dict = {
'somekey': 'somevalue'
};
val = dict['anotherkey'] || 'anotherval';
Simplest of all Solutions:
dict = {'first': 1,
'second': 2,
'third': 3}
Now,
dict['last'] || 'Excluded'
will return 'Excluded', which is the default value.
If you only have an object that is a single level deep (nested object properties will not merge as expected since it directly destructures from the first level), you can use the following destructuring syntax:
const options = {
somevar: 1234,
admin: true
};
const defaults = {
test: false,
admin: false,
};
var mergedOptions = {...defaults, ...options};
Of which the output would be:
console.log(options);
// { somevar: 1234, admin: true }
console.log(mergedOptions);
// { test: false, admin: true, somevar: 1234 }
Or even formatted as a single statement (this is slightly unreadable though):
const options = {...{
// Defaults
test: false,
admin: false,
}, ...{
// Overrides
somevar: 1234,
admin: true
}};
I saw an article yesterday that mentions an Object.__noSuchMethod__ property: JavascriptTips I've not had a chance to play around with it, so I don't know about browser support, but maybe you could use that in some way?
I'm surprised nobody has mentioned ternary operator yet.
var emptyObj = {a:'123', b:'234', c:0};
var defaultValue = 'defaultValue';
var attr = 'someNonExistAttribute';
emptyObj.hasOwnProperty(attr) ? emptyObj[attr] : defaultValue;//=> 'defaultValue'
attr = 'c'; // => 'c'
emptyObj.hasOwnProperty(attr) ? emptyObj[attr] : defaultValue; // => 0
In this way, even if the value of 'c' is 0, it will still get the correct value.
var obj = {
a: 2,
b: 4
};
console.log(obj);
--> {a: 2, b: 4}
function applyDefaults(obj) {
obj.a ||= 10;
obj.b ||= 10;
obj.c ||= 10;
}
// do some magic
applyDefaults(obj);
console.log(obj);
--> {a: 2, b: 4, c: 10}
This works because
undefined || "1111111" --> "1111111"
"0000000" || "1111111" --> "0000000"
as null, undefined, NaN, 0, "" (Empty String), false itself, are all considered to be equivalent to false (falsy). Anything else is true (truthy).
Note that this is not uniformly supported across browsers and nodejs versions (confirm for yourself).
So two troublesome cases are the empty String "" and 0 (zero). If it is important not to override those, you might need to rewrite this as:
if (typeof obj.d == "undefined") obj.d = "default"
This will be better supported across browsers also.
Alternatively you could write this as:
obj.d ??= "default"
This is the nullish assignment which applies only to values that are null or undefined (nullish) - of which the empty string is not part. However, this has again a diminished cross-browser support.
See also on the official Mozilla Website - Assigning a default value to a variable.
This is actually possible to do with Object.create. It will not work for "non defined" properties. But for the ones that has been given a default value.
var defaults = {
a: 'test1',
b: 'test2'
};
Then when you create your properties object you do it with Object.create
properties = Object.create(defaults);
Now you will have two object where the first object is empty, but the prototype points to the defaults object. To test:
console.log('Unchanged', properties);
properties.a = 'updated';
console.log('Updated', properties);
console.log('Defaults', Object.getPrototypeOf(properties));
Object.withDefault = (defaultValue,o={}) => {
return new Proxy(o, {
get: (o, k) => (k in o) ? o[k] : defaultValue
});
}
o = Object.withDefault(42);
o.x //=> 42
o.x = 10
o.x //=> 10
o.xx //=> 42
One approach would be to take a defaults object and merge it with the target object. The target object would override values in the defaults object.
jQuery has the .extend() method that does this. jQuery is not needed however as there are vanilla JS implementations such as can be found here:
http://gomakethings.com/vanilla-javascript-version-of-jquery-extend/
With the addition of the Logical nullish assignment operator, you can now do something like this
const obj = {}
obj.a ??= "default";
In the case where you have an empty list as the default value and want to push to it, you could do
const obj = {}
(obj.a ??= []).push("some value")
I came here looking for a solution because the header matched my problem description but it isn't what i was looking for but i got a solution to my problem(I wanted to have a default value for an attribute which would be dynamic something like date).
let Blog = {
title : String,
image : String,
body : String,
created: {type: Date, default: Date.now}
}
The above code was the solution for which i finally settled.

JS - Destructuring by picking only what you need [duplicate]

This question already has answers here:
Is it possible to destructure onto an existing object? (Javascript ES6)
(16 answers)
ES2015 deconstructing into an object [duplicate]
(1 answer)
How to get a subset of a javascript object's properties
(36 answers)
Closed 4 years ago.
I'm trying to understand ES6, specifically destructuring feature.
How can I translate these lines using destructuring?
const user = {...}
const sessionData = ({
session_id: user.session_id,
selector: user.selector,
validator: user.validator
})
I tried
const sessionData = {session_id, selector, validator} = user
But it raises a syntax error, because of course destructuring is for giving a certain variable a value from an object but I don't understand how to do something like this with an object
Use
const { session_id, selector, validator } = user;
Then
const sessionData = { session_id, selector, validator };
You could also do it like so (using anonymous functions)
const user = { session_id: 1, selector: "my-selector", validator: 1, unused: 3 };
const session = (({ session_id, selector, validator }) => ({ session_id, selector, validator }))(user);
console.log(session);
You can use a function to create the new object with the fields you want.
const original = { a: 1, b: 2, c: 3 };
const pick = (o, fields) => fields.reduce((acc, key) => {
acc[key] = o[key];
return acc;
}, {});
console.log(pick(original, ['a', 'b']));
Or use the comma operator to destructure and assign.
const original = { a: 1, b: 2, c: 3 };
const newone = ({ a, b } = original, { a, b });
console.log(newone);
But keep in mind that the comma operator creates global variables, if the variables to assign the destructure are not declared. Hope this helps.

Is there a purely functional way to merge objects in JavaScript?

Say I have an object with some properties:
const obj = {
key1: 1
key2: 2
}
and I have a function someFunc that takes one object as a parameter. I want to pass obj with some additional parameters, like
someFunc({
key1: 1
key2: 2
otherKey: 3
})
The problem is that I don't want to actually change the state of obj. After someFunc has been called it should not contain otherKey as a property.
This leaves Object.assign out of the question:
let ident = someObj => someObj;
ident(Object.assign(obj, {otherKey: 3}))
console.log(someObj); // -> {key1: 1, key2: 2, otherKey: 3}
Creating a new variable and assigning otherKey = 3 to it does the same thing.
I know I can use some sort of deep duplication - but that seems like an unnecessarily complex way of handling a fairly simple problem.
The most elegant way of doing this would be a pure function that takes some objects obj1, obj2, returns the same output as Object.assign(obj1, obj2), but alters neither of them. Is there some obvious way of doing this in JS that I haven't seen, or do I have to use some other library?
Just reverse the parameters to Object.assign - it will add the properties from obj to a new object:
ident(Object.assign({otherKey: 3}, obj))
Caution
But you must be careful about properties that are already present in obj as they will overwrite the ones in the new array.
You are dealing with immutability. Another way to accomplish thit is to use spread operator of ES6:
const obj1 = {
key1: 1,
key2: 2,
}
const obj2 = {
key1: 1,
key2: 12,
otherKey: 3
};
const merged = { ...obj1, ...obj2 };
console.log('merged: ', merged);
console.log('obj1: ', obj1);
console.log('obj2: ', obj2);
You'll see that neither obj1 nor obj2 is altered

What is this called in javascript? ({name, value}) => <span></span> [duplicate]

This question already has answers here:
What do curly braces inside of function parameter lists do in es6?
(3 answers)
Closed 6 years ago.
(in javascript)
In this context:
const component = ({ name, value }) => <span></span>
Where the first argument of the arrow function is separated to its members. props => ({ name, value })
What is this called? I've seen some people doing this with babel but don't know what the proper term is.
Where the first argument of the arrow function is separated to its members. props => ({ name, value }) ... What is this called?
It's called parameter destructuring (sometimes argument destructuring, it's the destructuring part that's important). What you pass the function is an object, but what the function receives are properties from the object. That is, they've been taken out of the structure (the object) and made into distinct things (hence, "destructuring"):
const adams = ({question, answer}) => {
console.log(question);
console.log(answer);
};
adams({question: "Life, the Unverse, and Everything!", answer: 42});
JavaScript has destructuring in a few places, including function parameter lists as above. You can also do it with assignments:
const o = {question: "Life, the Unverse, and Everything!", answer: 42};
const {answer, question} = o;
console.log(question);
console.log(answer);
There's a related feature in ES2018 and later (but it's been supported in JSX code for years via tranpsiling): The ability to get the "rest" of the properties as an object:
// ES2018+
const adams = ({question, answer, ...rest}) => {
console.log(question);
console.log(answer);
console.log(rest);
};
adams({
question: "Life, the Unverse, and Everything!",
answer: 42,
legend: true,
missed: true
});
That ...rest inside the {} in the parameter list creates an object with the "rest" of the properties (those not captured as discrete arguments). It's the destructuring version of JavaScript's "rest params." You can do it in assignments, too:
// ES2018+
const o = {
question: "Life, the Unverse, and Everything!",
answer: 42,
legend: true,
missed: true
};
const {question, answer, ...rest} = o;
console.log(question);
console.log(answer);
console.log(rest);
The ES2015 spec had it for arrays, ES2018 added it for object properties.
It's called destructuring.
Here's an example on how it works and how to use it:
const employeeOne = { name: 'John', phone: '555-5555', age: 27 };
const { name, phone, age: john_age } = employeeOne;
console.log(name); // 'John'
console.log(phone); // '555-5555'
console.log(john_age); // '27'
sayHi = ({ name }) => console.log(`Hello ${name}, how are you?`);
sayHi(employeeOne); //'Hello John, how are you?'

Categories

Resources