Destructure and retrieve the fully structured variable in one expression [duplicate] - javascript

This question already has answers here:
Destructure object parameter, but also have reference to the parameter as an object? [duplicate]
(2 answers)
Closed 3 years ago.
Is it possible to both destructure a variable and have access to the structured variable in the same call?
For example, what could I replace ??? below to get the desired output (and how else might I have to edit my code)
const foo = ({ a, b }) => {
console.log(a) // 1
console.log(b) // 2
console.log(???) // { a: 1, b: 2 }
}
const x = { a: 1, b: 2 }
foo(x)
My goal is knowledge and succinct code - I want to avoid const { a, b } = params as the first line of foo() in the case where I might need to pass the entire params object on.

If the first argument is an object whose reference you want, it's not possible - once you destructure an argument, there's no longer any way to reference to the full argument, only some of its properties.
It would be possible if the object and parts you wanted was part of a larger object, though, because then you can reference the property name alone (to get the object into a variable), and then reference it again to destructure, eg:
const foo = ({ obj: { a, b }, obj }) => {
console.log(a) // 1
console.log(b) // 2
console.log(obj) // { a: 1, b: 2 }
}
const obj = { a: 1, b: 2 }
foo({ obj })
Your original code could work to an extent if the object had a property that referenced itself, but that's pretty weird:
const foo = ({ a, b, obj }) => {
console.log(a) // 1
console.log(b) // 2
console.log(obj) // { a: 1, b: 2 }
}
const x = { a: 1, b: 2 }
x.obj = x;
foo(x)

Related

js reassign a value to multiple already declared variables from a function [duplicate]

This question already has answers here:
Return multiple values in JavaScript?
(20 answers)
JavaScript: How do I return two values from a function and call those two variables in another function?
(9 answers)
Object destructuring without var, let or const
(4 answers)
Closed 1 year ago.
I need to reassign the value of two differents variables. My code is like this:
const func = () => {
do something;
return {a, b}
}
Then I declare the two variables outside a if/else block with let :
let a = b = '';
And in the if/else i need to assign to the two variables the value returned form the function:
if(condition) {
a, b = func();
}
How can i reassign the value returned from the function to the variables?
You simply need to add parentheses around the assignment to have it parse as an expression rather than a block. MDN gives this example:
let a, b;
({a, b} = {a: 1, b: 2});
So in your case you would need
// For example
let a, b;
const func = () => ({a: 1, b: 2});
({a, b} = func());
You are mentioning errors, we don't see that, please make https://stackoverflow.com/help/minimal-reproducible-example for next time.
This is how it can be done:
const func = () => {
return ["a", "b"]
}
let a, b
if (true) {
const res = func()
a = res[0]
b = res[1]
console.log(a)
console.log(b)
}

is it possible to return the array with object property names? it's wired to ask to print the string without ' ' [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 2 years ago.
Write a function called myFun which has an object as its parameter and returns the name of properties of that object in an array. For instance, if it receives {a:1,b:3}, as its parameter, it should return [a, b], or if it receives {u:4, k:3, h:5}, it should return [u, k, h].
Note I am aware of Object.Keys(object) returns ['a', 'b', 'c']
//this function should return the name of the property
function myFun(object) {
object = {
a: 1,
b: 2,
c: 3
}
for (obj in object) {
console.log(obj);
}
}
myFun();
//testcase : console.log(myFun({a:6})[0]) which should return [a], is it
actually possible or am I asking the wrong question?
To get an array of object keys:
const keys = Object.keys(object);
To print them like you describe:
console.log(`[${keys.join(',')}]`);
Putting it together as a function:
function myFun(object) {
const keys = Object.keys(object);
return `[${keys.join(',')}]`;
}
This is the object's keys
var obj = {
a: 1,
b: 2,
c: 3
};
console.log(Object.keys(obj));

Why can I assign a value to a reference using array destructuring, but not object destructuring? [duplicate]

This question already has answers here:
Object destructuring without var, let or const
(4 answers)
Closed 2 years ago.
Using array destructuring I can assign a value to a reference:
const o = {}
;[o['something']] = ['a', 'b', 'c']
console.log(o) // { something: 'a' }
But I cannot do the same with object destructuring. Why?
const o = {}
{ ['1']: o['something'] } = { '1': 'a' } // Syntax Error
You can. The issue is just that the { } is interpreted as block here instead of an object literal! For the same reason you can't write { a: 1 }.a.
You can wrap the whole statement in parens to avoid this problem (in the same way as ({ a: 1 }).a makes the previous example work):
const o = {}
;({ ['1']: o['something'] } = { '1': 'a' })
console.log(o) // { something: 'a' }
A variable can be assigned its value with destructuring separate from its declaration using the parentheses ( ... ) around the assignment statement like:
const o = {};
({ ['1']: o['something'] } = { '1': 'a' });
console.log( o )
As mentioned in the docs,
The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.
{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.
However, ({a, b} = {a: 1, b: 2}) is valid, as is const {a, b} = {a: 1, b: 2}
Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

Shorthand for creating object with same field [duplicate]

This question already has answers here:
One-liner to take some properties from object in ES 6
(12 answers)
Closed 5 years ago.
const json = {
a: 1,
b: 2,
c: "HI"
}
Is there a way to just pass in {a : 1} to function?
var someReturn = aOnly({a : json.a});
I am not sure if destructuring/constructuring of ES6 solves this problem. I can't seem to find the right syntax after reading several ES6 destructuring example.
EDIT
Nothing is wrong with the code I am just asking if there is a syntax to just extract "a" only from JSON without redundantly doing
{a : json.a }
the implementation of aOnly function is not the focus here
You can use ES6 object destructuring on object passed as parameter to pick specific property.
const json = {
a: 1,
b: 2,
c: "HI"
}
function aOnly({a}) {
return a;
}
var someReturn = aOnly(json);
console.log(someReturn)
Thank you I have figured out the right syntax. The initial mistake I was doing was trying to construct directly using { json.a }, hoping that this will automatically turn into { a : json.a} but the right way is do destruct first and construct later.
var json = {
a : "ASDF",
b : 123,
c : "Test"
};
const {a, b, c} = json; // destructing
var aObject = aOnly({a}); // constructing
var bObject = bOnly({b});
var cObject = cOnly({c});
console.log (aObject);
console.log (bObject);
console.log (cObject);
function aOnly(a) { return a; }
function bOnly(b) { return b; }
function cOnly(c) { return c; }

indexOf but for objects? [duplicate]

This question already has answers here:
What's the correct way to test for existence of a property on a JavaScript Object?
(3 answers)
Closed 6 years ago.
I want to look through an object and assign each of it's existent properties to a variable.
There are 4 possible properties. Some of the objects have all 4. Some might only have two.
How can I check if a particular property exists? Is there an equivalent of indexOf() for arrays but for objects instead?
Use the in keyword:
"key" in object
which returns true or false, depending if the object, or anything in its prototype chain, has that property.
You can also use object.hasOwnProperty("key"), which will only be true if the object has key as a property of itself, not its prototype. Example:
var object = {};
"toString" in object; // true
object.hasOwnProperty("toString"); // false
Note (as per #dandavis's comment) that if object has a custom property called hasOwnProperty, this gets thwarted; to work around this, use hasOwnProperty.call(object, "key"). Example:
var a = {hasOwnProperty: Boolean};
a.hasOwnProperty('name'); // true
hasOwnProperty.call(a, 'name'); // false
If you are only interested in properties set directly on the object (not accessible via the prototype chain) then hasOwnProperty will provide a boolean value, true, if an object has the specified property.
For example: testObject.hasOwnProperty('propertyToCheckFor') would return true if testObject.propertyToCheckFor exists, otherwise it would be false.
See the following code for a more expanded example:
var obj1 = {
a: 1
};
var obj2 = {
a: 1,
b: 2
};
var obj3 = {
b: 2,
c: 3
};
var obj4 = {
a: 1,
b: 2,
c: 3
};
// For dispaly purposes
document.write('<pre>' + JSON.stringify({
obj1: {
hasA: obj1.hasOwnProperty('a'),
hasB: obj1.hasOwnProperty('b'),
hasC: obj1.hasOwnProperty('c')
},
obj2: {
hasA: obj2.hasOwnProperty('a'),
hasB: obj2.hasOwnProperty('b'),
hasC: obj2.hasOwnProperty('c')
},
obj3: {
hasA: obj3.hasOwnProperty('a'),
hasB: obj3.hasOwnProperty('b'),
hasC: obj3.hasOwnProperty('c')
},
obj4: {
hasA: obj4.hasOwnProperty('a'),
hasB: obj4.hasOwnProperty('b'),
hasC: obj4.hasOwnProperty('c')
}
}, null, 2) + '</pre>');
var obj = {
foo: 1,
bar: 2,
baz: 3
}
Object.keys(obj).forEach(function(key) {
window[key] = obj[key]
})
console.log(foo, bar, baz)
Or in ES2015
const obj = {
foo: 1,
bar: 2,
baz: 3
}
function assignPrivateVars() {
let {foo, bar, baz} = obj;
console.log(foo, bar, baz);
}
assignPrivateVars();
You can use destructuring assignment. If value is not defined, variable will be set to undefined. You can also check if variable is defined after destructuring then delete variable by reference.
var data = {a:1, b:2, c:3};
var {a, b, c, d} = data; // `d`: `undefined`

Categories

Resources