I have an object like this which I console log like this:
console.log(node.data.target.fields);
file:
en-US: {url: "//images.ctfassets.net/qkwv5aiilkmk/4YsaPFrSxMPKuMVnO/efb6b59a369e4f30105aaea54fb9f62f/aaa.jpeg", details: {…}, fileName: "aaa.jpeg", contentType: "image/jpeg"}
I want to access the url value but It throws an error :
const url = node.data.target.fields.file.['en-US'].url;
How can I access the en-Us variable properly?
Since en-US cannot be used as a variable name (- is an operator, cannot be used as a part of a variable), you cannot use the dot notation. So the only way you can access is using the [] notation.
const url = node.data.target.fields.file['en-US'].url;
The above is the right way of accessing it, else, you can also access this way:
const lang = 'en-US';
const url = node.data.target.fields.file[lang].url;
Two cases example:
const node = {
data: {
target: {
fields: {
file: {
"en-US": {
url: "//images.ctfassets.net/qkwv5aiilkmk/"
}
}
}
}
}
};
(() => {
console.log("Using direct access...");
const url = node.data.target.fields.file['en-US'].url;
console.log(url);
})();
(() => {
console.log("Using a variable...");
const lang = 'en-US';
const url = node.data.target.fields.file[lang].url;
console.log(url);
})();
To add from the given answer just a few guidelines for accessing Object Properties here are some tips that would help you in the future.
1. Dot property accessor
This common way to access the property of an object is the dot property accessor syntax:
expression.identifier
const hero = {
name: 'Batman'
};
// Dot property accessor
hero.name; // => 'Batman'
1.1 Dot property accessor requires identifiers
-The dot property accessor works correctly when the property name is a valid identifier. An identifier in JavaScript contains Unicode letters, $, _, and digits 0..9, but cannot start with a digit.
const weirdObject = {
'prop-3': 'three',
'3': 'three'
};
weirdObject.prop-3; // => NaN
weirdObject.3; // throws SyntaxError: Unexpected number
To access the properties with these special names, use the square brackets property accessor (which is described in the next section):
const weirdObject = {
'prop-3': 'three',
'3': 'three'
};
weirdObject['prop-3']; // => 'three'
weirdObject[3]; // => 'three'
2. Square brackets property accessor:
-expression[expression]
const property = 'name';
const hero = {
name: 'Batman'
};
// Square brackets property accessor:
hero['name']; // => 'Batman'
hero[property]; // => 'Batman'
3. Object destructuring:
const { identifier } = expression;
const hero = {
name: 'Batman'
};
// Object destructuring:
const { name } = hero;name; // => 'Batman'
Note that you can extract as many properties as you’d like:
const { identifier1, identifier2, .., identifierN } = expression;
Related
I had read this post How to return values in javascript. But my question is how do we get the Map value if we derived it from asynchronous function like in this code below:
async function exampleToken(profile) {
let response;
const tkAdmin = {
admin: true,
};
const tkInvestors = {
investor: true,
};
if (profile == 1) {
response = {
"token": tkAdmin,
"code": 1,
};
} else if (profile == 2) {
response = {
"token": tkInvestors,
"code": 2,
};
}
return Promise.resolve(response);
}
I want to use the value from this function using this code:
const response = await exampleToken(profile);
// Is this correct:
const code = response.code;
const token = response.token;
// or
const code = response["code"];
const token = response["token"];
Please, help me out. Any tips and trick will be great. Thank you very much for spending time to read this post.
Both are correct in Javascript,
1- Dot property accessor: object. property.
2- Square brackets property access: object['property']
3- Object destructuring: const { property } = object.
This style is named Object Dot Notation access
const code = response.code;
const token = response.token;
and this one is Object Bracket notation access
const code = response["code"];
const token = response["token"];
Read more here
I created a function that should return an object with user data. I want the function to accept an object as a parameter and I'd like this object to be defined inside the function with all the values pre-defined as default parameters in case they are not passed at a function call. The example code has only 2 values but I will need to pass over 15. How can I achieve such a solution?
const userCreator = (name, age) => {
if (name === undefined) {
name = 'John'
}
if (age === undefined) {
age = 25
}
return {
name:name,
age:age
}
};
...and I'd like this object to be defined inside the function with all the values pre-defined as default parameters in case they are not passed at a function call.
I think you're saying:
You want the function to accept an object
You want all the properties of that object to be optional with defaults specified by the function
To do that, you can use destructuring defaults. But see also below, because in this specific case, where you want to return an object, you may want to use a different approach.
But let's start with just basic destructuring without defaults, then add them:
const userCreator = ({ name, age }) => {
// ^−−−−−−−−−−−^−−−−−−−−−−−−−−−− destructuring
// ...stuff with `name` and `age` here...
return {
name,
age,
};
};
To add defaults for those properties, you add them within the destructuring pattern (the {} where the parameter name would otherwise be):
const userCreator = ({ name = "John", age = 25, }) => {
// ^^^^^^^^^−−−−−^^^^^−−−− defaults for the properties
return {
name,
age,
};
};
If there are lots, probably best to break up into lines:
const userCreator = ({
name = "John",
age = 25,
}) => {
return {
name,
age,
};
};
That version still expects an object to be provided, though. If you want to allow userCreator() (no parameter passed at all), you need to add a default parameter value for the object parameter:
const userCreator = ({
name = "John",
age = 25,
} = {}) => {
//^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−− default for the parameter
return {
name,
age,
};
};
That uses {} as the default value if no parameter is provided at all, "John" as the default if name isn't provided, and 25 as the default if age isn't provided. And since there is no name or age on the default {}, they get defaulted when you do userCreator().
The alternative approach:
Since you want to return an object, you might just accept the object parameter directly, then use property spread or Object.assign to fill in defaults, like this:
const userDefaults = {
name: "John",
age: 25,
};
const userCreator = (template) => {
const result = { // The result object we'll return
...userDefaults, // Fill in defaults
...template // Overwrite with any properties from the caller
};
// Or with `Object.assign` in older environments without property spread:
//const result = Object.assign(
// {}, // The result object we'll return
// userDefaults, // Fill in defaults
// template // Overwrite with any properties from the caller
//);
return result;
};
Property spread and Object.assign both ignore null or undefined, so if no object is passed at all, template is undefined, and
You should define default values directly in the function parameters:
const userCreator = (name = 'John', age = 25) => {
return {
name: name,
age: age
}
};
This question already has answers here:
One-liner to take some properties from object in ES 6
(12 answers)
Closed 1 year ago.
I have an object adData and I need to extract some of it's properties, add some more properties to the extracted object and pass the object as parameter. I can do this using:
const params = {};
params.id = adData.id;
params.status = adData.status;
params.frequency = adData.frequency;
params.user = getLoggedInUser();
callAnotherFunction(params)
Can I do the destructing and reassigning to new object in one line ? Something like:
const params = {id, status, frequency} = adData;
params.user = getLoggedInUser();
Or
const params = {id, status, frequency, getLoggedInUser(): user} = adData;
Now these both above syntaxes are wrong but is there any other way to do it using destructuring and without extracting the properties one by one
If you know what properties the object does have, and there aren't that many, you can list them and use rest syntax to gather the others into an object:
const { unwantedProp, ...params) = adData;
// use params
Otherwise, there isn't any incredibly simple syntax for what you want, though you could
const params = Object.fromEntries(
Object.entries(adData).filter(([key]) =>
['id', 'status', 'frequency'].includes(key)
)
);
We can do in one line with destructuring and arrow function.
const getLoggedInUser = () => "foo";
const adData = {
id: 123,
status: "active",
frequency: "less",
bar: 4,
};
const params = (({ id, status, frequency }, user = getLoggedInUser()) => ({
id,
status,
frequency,
user,
}))(adData);
console.log({ params });
Is there any way to define a string value like a shorthand property, something like e.g. (this doesn't work):
const dict = {
USER_LOGIN,
USER_LOGOUT
};
Which will be equivalent to:
const dict = {
USER_LOGIN: "USER_LOGIN",
USER_LOGOUT: "USER_LOGOUT"
};
I want to define a constants dictionary, but I was wondering if I can somehow avoid the repetition pattern MYVALUE : "MYVALUE".
Is there any shorthand way of declaring object keys with values equivalent to their string values, similar to the (not working) code above?
There's no built-in way to do something like that automatically, but if you want to keep the code DRY, you can make a helper function that, when passed an array of strings, creates an object with those properties:
const makeDict = arr => arr.reduce((a, str) => ({ ...a, [str]: str }), {});
const dict = makeDict(['USER_LOGIN', 'USER_LOGOUT']);
console.log(dict);
Shorthand property notation will only work when you have a variable having the same name as the property you want to declare:
const USER_LOGIN = 'USER_LOGIN';
const USER_LOGOUT = 'USER_LOGOUT';
const dict = {
USER_LOGIN,
USER_LOGOUT
};
console.log(dict);
Otherwise, you have to specify the whole object:
const dict = {
USER_LOGIN: "USER_LOGIN",
USER_LOGOUT: "USER_LOGOUT"
};
Or create it via a helper as #CertainPerformance mentionned.
You can declare them and use those constants as key-value on an object.
const USER_LOGIN = "USER_LOGIN";
const USER_LOGOUT = "USER_LOGOUT";
const dict = { USER_LOGIN, USER_LOGOUT };
console.log(dict);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Just kidding:
let dict;
with(new Proxy({}, {
get(_, key) { return key; },
has(_, key) { return key !== "dict"; }
})) {
dict = {
USER_LOGIN,
USER_LOGOUT
};
}
console.log(dict);
If you think that does not work... just try it :)
But seriously: The whole question is just overkill.
Today I came across the following syntax which I didn't recognize:
const createUser = ({
age = 1,
name = 'Anonymous',
}) => ({
age,
name,
});
const defaultP = createUser({
age: 5
});
console.log(defaultP);
I think it uses Object destructuring and default parameters in order to set defaults of the object which is send as an argument.
The syntax threw me a bit off because normally I see object destructuring only in the following manner:
let obj = {
prop1: 1
}
const {prop1} = obj;
console.log(prop1);
Question:
How does this syntax work exactly?
That syntax indeed uses Object Destructuring in order to extract default values from the parameter object. There are some examples in the Mozilla documentation that helps us understand the trick, check this out:
var {a = 10, b = 5} = {a: 3};
console.log(a); // 3
console.log(b); // 5
A possible disadvantage of your example is that the createUser method ignores all other values of the parameter object and always returns an object that contains only age and name. If you want to make this more flexible, we could use Object.assign() like this:
const createUser = (o) => Object.assign({ age: 1, name: 'Anonymous' }, o);
In this case, the user created will be an object that merges the parameter object with the default values. Note now that the default values are in the method body. With this method we can create users that contain other properties, example:
const superman = createUser({ name: 'Superman', type: 'superhero' });
console.log(superman);
// output: {age: 1, name: "Superman", type: "Superhero"}
Your code is using both Object Destructuring and default function props.
const createUser = ({
age = 1,
name = 'Anonymous',
}) => ({
age,
name,
});
Here function createUser is accepting single argument of type Object. Function is returing same object, if you have both object properties defined in your argument, then it will return your passed object. Otherwise it will replace it with default values, which are 1 and Anonymous respectively.
You can further read about it here:
https://wesbos.com/destructuring-renaming/
https://wesbos.com/destructuring-default-values/
If you use babel and transpile your code to ES5, it will look like this:
function createUser(params) {
return {
age: typeof params.age === 'undefined' ? 1 : params.age,
name: typeof params.name === 'undefined' ? 'Anonymous' : params.name,
};
}
Just a note: default values for function arguments works the same way:
const multiply = (a, optionalB) => {
const b = typeof optionalB !== 'undefined' ? optionalB : 2;
return a * b;
}
Is same as:
const multiply = (a, b = 2) => {
return a * b;
}
It increases a readability, mostly in cases when argument is used several times.