This question already has answers here:
Object destructuring without var, let or const
(4 answers)
Closed 4 years ago.
So I'm trying to figure out if there's any simple ES6 syntax to do the following:
If I have an object
const config = { foo: null, bar: null }
And I want to assign the values of those properties from another object such as:
const source = { hello: "hello", world: "world", another: "lorem", onemore: "ipsum" }
I want to do something like the following but it doesn't work
{ hello:config.foo, world:config.bar } = source
I know I can do something very close like:
{ hello:foo, world:bar } = source
But this creates new variables foo and bar, whereas I want to assign to existing properties on another object. I'm just curious if there's an ES6 shorthand for this; I don't need help doing this with traditional code, I know there are a dozen ways and I already know most of them.
You're just missing brackets () around the statement.
const config = {};
const source = { hello: "hello", world: "world", another: "lorem", onemore: "ipsum" };
({hello: config.foo, world: config.bar} = source);
console.log(config);
Related
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 3 years ago.
I hope you are very well.
I am trying to find an complex object in an Object in Angular from a String (the content of this String is dynamic).
For example:
let variable = {
"name":"Rick",
"family": {
"son":"Andy"
}
};
When I try to read the name attribute, I can find it with the code:
console.log(variable["name"]);
When I try to read the family attribute, I can find it with the code:
console.log(variable["family"]);
However when I try to read the son attribute, I have tried to make with the code:
console.log(variable["family.son"]);
But I have gotten an undefined value, I found that I can use any of the followings codes:
console.log(variable["family"]["son"]);
console.log(variable["family"].son);
But it is not working for me, because I need to search the attribute from a String (the attributes are Dynamics), Does someone know how can I solve this.
The String contains the attribute path, for instance: "family.son" or "family"
Regards.
Try something like this:
const dotPathAccessor = (src, path) => {
const parts = path.split('.');
return parts.reduce((obj, prop) => obj[prop], src);
}
const variable = {
"name": "Rick",
"family": {
"son": "Andy"
}
};
console.log(dotPathAccessor(variable, "family.son"));
// you can use a Proxy object to make it simpler
// with this prototype, you can now get a dot proxy for any object using `object.getDotProxy`
// and access it using dot paths
Object.prototype.getDotProxy = () => new Proxy(variable, {
get(obj, prop) {
return dotPathAccessor(obj, prop);
}
});
const dotProxy = variable.getDotProxy();
console.log(dotProxy["family.son"]);
This question already has answers here:
Javascript object bracket notation ({ Navigation } =) on left side of assign
(5 answers)
Syntax: const {} = variableName, can anyone explain or point me into the right direction [duplicate]
(1 answer)
Closed 4 years ago.
On this page (https://nodejs.org/api/modules.html), I found this writing: { }.
const { PI } = Math;
Does it have a particular name, so that I can get more information about it, and especially what does it produce?
Thanks in advance. :D
This is called "destructuring assignment". You can think of it as being equivalent to:
const PI = Math.PI;
…but a little more compact. It really shines when being used to pluck multiple properties off an object:
const { foo, bar, baz } = require('quux').util;
You can also destructure arrays using [ ]:
const [ first, second, third ] = array;
The curly brackets in javascript typically represent an object, but in this case, it is a "destructuring assignment". For example:
const obj = { value: 'hello world' };
const {value} = obj;
console.log(value); // outputs: hello world
This question already has answers here:
Is it possible to destructure onto an existing object? (Javascript ES6)
(16 answers)
Closed 4 years ago.
TLDR: How to use destructuring to speed up updating parts of one object based on another object of the same interface?
I would like to use the new ECMA2015 - 2017 JavaScript to refactor my code.
For simplicity let's say I have an object, looking like this:
export interface myObj {
name: string;
id: number;
description: string;
someBool: boolean;
anotherBool: boolean;
}
(Export interface works, because I'm working in Angular using Typescript).
Here is the old es5 function:
updateMyObj = function(oldObj, newObj) {
var someBoolSaved = oldObj.someBool;
var anotherBoolSaved = oldObj.anotherBool;
oldObj = newObj;
oldObj.someBool = someBoolSaved;
oldObj.anotherBool = anotherBoolSaved;
}
As you can see the function should update some parts of the oldObj, but also keep some parts.
Here is my attempt at refactoring the code:
updateObj(oldObj, newObj) {
let {someBool, anotherBool} = oldObj;
oldObj = newObj;
// Here is the part where I don't know how to proceed.
}
But I don't know, how I can now assign the oldObj's bools to the saved bools.
An inelegant way would be
oldObj.someBool = someBool;
oldObj.anotherBool = anotherBool;
which in this example would be fine. But in my actual task, this costs many lines of code which is why I want to refactor.
I just can't figure out the right syntax.
My attempts at coding this look similar like this:
oldObj = {someBool, anotherBool}
but this doesn't work.
If you want to assign the destructured value to a property, you do that by specifying the property on the right-hand side of a : in the destructuring.
For instance: The following assigns newObj.a and newObj.c to oldObj.a and oldObj.c:
({a: oldObj.a, c: oldObj.c} = newObj);
// ^^^^^^^^-----^^^^^^^^---- destinations for a and c
(The () are necessary because otherwise the { at the beginning looks like the beginning of a block. If we were already in an expression context, you wouldn't need them.)
const oldObj = {a: "old a", b: "old b"};
const newObj = {a: "new a", c: "new c"};
({a: oldObj.a, c: oldObj.c} = newObj);
console.log(oldObj);
As Bergi points out in a comment on the question, it doesn't really buy you much over
oldObj.a = newObj.a;
oldObj.c = newObj.c;
That's one reason various pick notations have kicked around (that one's seen activity quite recently). If that proposal were accepted (and it doesn't even have a champion yet, so don't hold your breath), you'd have oldObj.{a, c} = newObj;.
const newObj = { ...oldObject, someBool: true, anotherBool: false};
Edit:
Is updating the old object really what you want to do?
In your original code you mutate oldObj as a side-effect of the function. This is generally regarded as bad practise. The following is an example of a pure function with no side effects.
const firstObj = { name: 'hi', someBool: true, anotherBool: true };
const secondObj = { name: 'bye', someBool: false };
const thirdObj = mergeObjects(firstObj, secondObj);
// work with thirdObj from now on
function mergeObjects(firstObj, secondObj): myObj {
return {
...secondObj,
firstObj.someBool,
firstObj.anotherBool
}
}
This question already has answers here:
beginner's: const definition in Redux confusing
(1 answer)
What does curly brackets in the `var { ... } = ...` statements do?
(4 answers)
Closed 5 years ago.
What is this code convention in javascript?
const { navigate } = //whatever
As in, what sense does it make. I saw it in RNs React navigation
https://reactnavigation.org/docs/intro/
It's named destructuring. When you have an object and you want to take only a property of that object, you can get only it by using that convention.
let fullName = {
first: 'John',
last: 'Smith'
}
const { first } = fullName;
You can take a look here for more info's
http://wesbos.com/destructuring-renaming/
It's called destructuring
Example:
var myObject = {a: "what", b: "ever"};
const {a} = myObject;
console.log(a); // will give "what"
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 7 years ago.
I know that you can evaluate the value of a property inside of a JS object, like the following:
let object = {
value: 5+5
};
I am wondering if there is any possible way to evaluate the name of an attribute with JS, i.e. achieve the following:
let object;
object[5+5].value = "ten";
As something like:
let object = {
5+5: "ten"
};
Yes in ES2015, no in ES5, but first let's clear one thing up: that's JavaScript, not JSON.
In ES2015 (formerly known as ES6):
var something = "foo";
var object = {
[something]: "bar";
};
alert(object.foo); // "bar"
Inside the [ ] can be any expression you like. The value returned is coerced to a string. That means you can have hours of fun with stuff like
var counter = function() {
var counter = 1;
return function() {
return counter++;
};
};
var object = {
["property" + counter()]: "first property",
["property" + counter()]: "second property"
};
alert(object.property2); // "second property"
JSON is a serialization format inspired by JavaScript object initializer syntax. There is definitely no way to do anything like that in JSON.
Sure. Try this:
'use strict';
let object = {
[5+5]: "ten"
};
console.log(object); // Object {10: "ten"}