Automatically assign variables when destructuring large objects in ES6 [duplicate] - javascript

This question already has answers here:
How do I destructure all properties into the current scope/closure in ES2015?
(5 answers)
Closed 2 years ago.
I think I understand destructuring in ES6 well enough. Example:
const obj = {
foo: 'String1',
bar: 'String2'
}
let { foo, bar } = obj
console.log(foo) //Prints "String1"
Simple enough.
However, I have a large object with a dynamic number of properties with dynamic names. I'd like to be able to assign them automatically.
Example object:
const obj = {
a: 'String1',
b: 'String2',
c: 'String3',
// ....
y: 'String25',
z: 'String26',
}
Instead of declaring each variable individually, I tried:
// Instead of
// { a, b, c, d, so_on, y, z } = obj
// I try:
let { ...obj } = obj
But get this error:
Identifier 'obj' has already been declared
What's a better way to approach this?

As long as the identifier is different than that of the object you're trying to destructure it should work exactly as you intend it to.
const obj = {
a: 'String1',
b: 'String2',
c: 'String3',
// ...
y: 'String25',
z: 'String26',
}
const { a, b, ...rest } = obj
// const a: 'String1'
// const b: 'String2'
// const rest: {
// c: string;
// ...
// y: string;
// z: string;
// }
See this example in the playground.

Related

How to use object rest operator to omit properties dynamically

I'm using the ES7 Object Rest Operator to Omit Properties from an object, but I'd like to make it more flexible so that I can dynamically provide the list of properties to exclude.
const myObject = {
a: 1,
b: 2,
c: 3
};
const { a, ...noA } = myObject;
console.log(noA); // => { b: 2, c: 3 }
Is there a way to make this more dynamic such that I can call a function and provide an array of properties to exclude instead of the hardcoded approach taken with properties a and b in this example?
Ideally I could have something along these lines -- but this syntax is invalid:
function omitProperties(myObj, fieldsToExclude) {
const { ...fieldsToExclude, ...noA } = myObj;
console.log(noA); // => { b: 2, c: 3 }
}
omitProperties(myObject, [`a`]);
You can consider _.omit.
You can also consider the following:
let omitProperties = (props, exclude) => {
let result = { ...props };
for (let propName of exclude) delete result[propName];
return result;
};
There's quite a bit of discussion about this same issue here.

Printing deepcopy of an object using custom function

I need to print elements of an object which is a deepcopy of another object using custom function. I am able to create deep copy using JSON parse/stringify trick but unable to implement print function.
var obj = {a:1,
b:{
a:2,
c:[1,2,3],
d:{
a:3
}
}
};
const mySnapShot = new Snapshot(object);
mySnapshot.print('a')// 1
.print('b.c') //[1,2,3]
.print('b.a') // 2
Arguments passed in print method are string. Snapshot is a class which contains methods for deep copy and print.
You can use reduce:
var obj = {
a: 1,
b: {
a: 2,
c: [1, 2, 3],
d: {
a: 3
}
}
};
function print(path) {
const pathTokens = path.split('.');
const pathValue = pathTokens.reduce((subObj, pathToken) => {
return subObj && subObj[pathToken] || null
}, obj);
return pathValue;
}
console.log(print('a')) // 1
console.log(print('b.c')) //[1,2,3]
console.log(print('b.a')) // 2

Is There a Object pollution while initializing values in a constructor using Object.keys?

I have an sample class defined as below
class Constants {
constructor(keysObj) {
this.keysObj = keysObj
Object.keys(this.keysObj).forEach((k) => this[k] = keysObj[k])
}
function getInformation() {
console.log("This is default function")
}
}
So when I create a object of above class - I can access the values as below
var newConsts = new Constants({
a: 1,
b: 2,
c: 3
})
// so I can access above values in this way
console.log(newConsts.c) // outputs 3
console.log(newConsts.getInformation) // outputs "This is default function"
Is code is vulnerable to Object Pollution ?
what I observed so far is - if I create a new object like this
var newConsts1 = new Constants({
a: 1,
b: 2,
getInformation: function() {
console.log('This is modifed')
}
})
// so I can access above values in this way
console.log(newConsts1.b) // outputs 2
console.log(newConsts1.getInformation) // outputs "This is modifed"
is Object pollution can be done on this class? if so please let me know what are the different ways to pollute it.
will this have any effect on the code
var newConsts3 = new Constants({
a: 1,
b: 2,
__Proto__: {
toString: function() {
console.log('faulty toString Executed')
}
}
})
var newConsts3 = new Constants({
a: 1,
b: 2,
prototype: {
construtor: undefined
}
}
})
the short answer is YES.
and this is because you are not checking in a safe mode that the keys that you are "initializing" are good or not, therefore, you can send anything to your object and make it vulnerable.

I am curious about javascript destructuring

The destructuring is one of the javascript syntax
This have been used like this.
const obj = { a: { A: 1, B: 2 } };
const { a } = obj // this is obj.a
const { B } = a // this is obj.a.B
the thing that I want to know is destructuring can save memory?

JavaScript Function Returns Multiple Values as Object in ES6

function function_name()
{
var a=1;
var b=2;
return {a, b}
}
let {p1, q1} = function_name()
Why do I get an error message about the values of p1, q1 as undefined? However, the below code gives the expected results:
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true
Can any one please explain the difference between the two code examples?
You are getting desired output because function_name() is returning an object that is having two variables a and b having some value.
function function_name()
{
var a=1;var b=2;
return {a,b}
}
here return {a, b} is equivalent to return {a: a, b: b} is equivalent to return {a: 1, b: 2}
To get the exact value you need to update your calling method signature to:
let {a, b} = function_name()
Note: It is not a good practice to use a or b as variable name. You should use valid names.
It is a destructuring, which uses the keys in the curly bracket for getting the values with the same key of the assignment. Your function retuns an object
{ a: 1, b: 2 }
and then you want to get the properties with the names p1 and p2. Obviously there are no keys with this names in the object and therefor no property in the result.
{ a: 1, b: 2 } => get { p1 and p2 } => {}
Working example
{ p: 42, q: true } => get { p and q } => { p: 42, q: true }
With another property
{ p: 42, q: true, foo: 42 } => get { p and q } => { p: 42, q: true }
Use like this
function function_name()
{
var a=1;
var b=2;
return [a, b]
}
let [p1, q1] = function_name()
return multiple values as array

Categories

Resources