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; }
Related
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 29 days ago.
In JS/typescript, lets say I have an object like this
var obj = {
a: {
b:{
c:1
}
}
}
And I have a string "b.c". How can I evaluate this using only those variables and get the value 1 from the object without using hacks like eval since typescript would complain.
Thanks
It I understood you question, the keys are known, if so you can use the '[]' to access it :
const a = b.c
is the same thing as
const a = b['c']
but in the second case you can of course use a variable.
Applying this to your object, it would look something like this :
const obj = {
a: {
b: {
c: 1
}
}
}
const outerKey = 'a'
const middleKey = 'b'
const innerKey = 'c'
const value = obj[outerKey][middleKey][innerKey]
console.log(value)
Hope it helped you !
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)
}
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)
This question already has answers here:
Checking if a key exists in a JavaScript object?
(31 answers)
Closed 4 years ago.
Trying to figure out what the easiest way to write a function keyExisits that checks and arbitrarily nested key to see if it exists in an object and is undefined, vs does not exisit.
assume this obj
var obj = {
a: {
b: 1,
c: {
d: 2,
e: undefined
}
}
}
In this object the key a.c.e exists and is undefined, the key a.c.f does not exist
so
keyExists(obj, 'a.c.e') === true
keyExists(obj, 'a.c.f') === false
using lodash/underscore is ok
** UPDATE **
Lodash has works exactly like this
You can try following
var obj = {a: {b: 1,c: {d: 2,e: undefined}}};
function keyExists(o, key) {
if(key.includes(".")) {
let [k, ...rest] = key.split(".");
return keyExists(o[k], rest.join("."));
} else if(o) {
return o.hasOwnProperty(key);
}
return false;
}
console.log(keyExists(obj, 'a.c.e') === true)
console.log(keyExists(obj, 'a.c.f') === false)
Note: The above code will not work if there are any dots in the key name or you are using [] notation.
This question already has answers here:
How do I reference the same Object's properties during its creation? [duplicate]
(5 answers)
Closed 9 years ago.
Can one reference own properties on initialization of object?
I have an object that should be unique and only exist as one so I
have no initializer etc.
Using something like this:
var Myobj = {
property1 : aaa,
property2 : bbb,
property3 : {a: self.property1 }
/* ^-- is this somehow possible without using a function?
Or a better way to solve / structure this. .init()
best option? */
};
>> Fiddle <<
The real object, (in the real code), has an add function that takes options on
what function to use etc. It is sort of a wrapper for "addEventListener" where
the point is to be able to remove listener - which require non anonymous function
reference.
Function to use within Myobj is specified by string, or numeric key in options to
Myobj.add().
Object literals remain undefined until the closing }, so you'd either have to make property3 a function or make the whole object a function.
var Myobj = {
property1 : 'aaa',
property3 : function (){ return { a : this.property1 } }
};
or
var MyObj = function(){
this.property1 = 'aaa',
this.property3 = { a: this.property1 }
}
var MyObjInstance = new MyObj();
This has been asked a lot of times: Access properties while declaring object?
It works if you use a placeholder array:
var prop = new Array();
var Myobj = {
property1 : 'aaa',
property2 : 'bbb',
property3 : {a: prop}
};
prop.push(Myobj.property1);
window.alert(Myobj.property3.a);
http://jsfiddle.net/y2XwC/1/