This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 3 years ago.
I have an array of strings that I get from an endpoint and I need to convert it to key-value pairs for the frontend to display them correctly. I have tried different concepts such as reduce and map but have not been able to get it working successfully. I assume it might be one-liner for someone familiar with FE but has taken forever for a BE person like me.
Here is what I have tried:
var input = ['quiz1', 'quiz2'];
const mapping = input.map(x => {"id":x, "label":x};);
console.log(mapping);
I am expecting an output of the format
[{"id":"quiz1", "label":"quiz1"}, {"id":"quiz2", "label":"quiz2"}]
Thanks for looking!
It's simply two syntax errors:
var input = ['quiz1', 'quiz2'];
const mapping = input.map(x => ({"id":x, "label":x}));
console.log(mapping);
Firstly, no semicolon in a un-braced arrow function body.
This is invalid: (() => 3;). This is valid: (() => 3).
Secondly, wrap return obj in ().
This is invalid: () => {x: 3}. This is valid: () => ({x: 3}).
Related
This question already has answers here:
SyntaxError Unexpected token, expected ","
(1 answer)
The use of brackets in javascript arrow function declaration
(1 answer)
Syntax for destructuring arrays into function parameters in ES6
(1 answer)
Closed 1 year ago.
Is there a way in which I can destructure an array in the parameters of its prototype functions?
For example, I can use an Array.prototype function such as forEach to evaluate the value of each array element and log an individual sub-array value using bracket notation:
const array = [[0,1],[3,4],[5,6]];
array.forEach(element => console.log(element[0]));
// -> 0
// -> 3
// -> 5
If I want to refer to a sub-array element by an assigned name, can I do so with destructuring? Currently, I know I can do it like this:
let array = [[0,1],[3,4],[5,6]];
array.forEach(element => {
let first = element[0];
let second = element[1];
console.log(first);
// -> 0
// -> 3
// -> 5
});
What I would like to achieve using destructuring is assigning these variable names the way you normally would with destructuring in a typical function's parameters:
let array = [[0,1],[3,4],[5,6]];
array.forEach([first, second] => console.log(first));
// Uncaught SyntaxError: Malformed arrow function parameter list
Is this possible?
After a little bit of trial and error, it appears this is fully possible. You just have to wrap the restructuring parameter in parentheses the same way you would if there were multiple parameters:
let array = [[0,1],[3,4],[5,6]];
array.forEach(([first, second]) => console.log(first));
// -> 0
// -> 3
// -> 5
This question already has answers here:
access object through dot-syntax string path
(2 answers)
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 2 years ago.
I am having a problem which I think I might have figured out before how to do it but I can't remember now and can't figure it out.
Let's say we have an object thats a few levels deep, meaning it has as values other objects which also have as some of the values objects and so on.
Now how could I make a function to which I pass the object and and adress inside it and I can access the value at that location inside the function like this:
const getValueAtAdress = (object, 'country.city.rules') => {
return //here I need to return the value at object.country.city.rules.
}
Am I missing something obvious?
I thought I'd mention here for posterity that what helped me was the answer using the reduce which is exactly what I used before but I could not remember:
Example that I am using for my particular problem:
let stateLocation = address.split('.').reduce((acc, cur) => acc[cur], state);
Your code shows a function declaration but you can't declare an argument name in quotes
You can however call a function and pass a string.
In that case, you just need to split the string into an array and then loop over that array, building up a "chained" set of string indexes that can be passed to the object. The String.split() and Array.reduce() methods are the key.
let obj = {
county: {
city: {
rules: "Strict"
}
}
};
const getValueAtAddress = (object, countyCityRules) => {
// Split the string at the dots to form an array...
// The loop over that array and reduce it with an
// accumulator that is then applied to the object.
return countyCityRules.split(".").reduce((acc, cur) => acc[cur], obj);;
}
console.log(getValueAtAddress(obj, "county"));
console.log(getValueAtAddress(obj, "county.city"));
console.log(getValueAtAddress(obj, "county.city.rules"));
This question already has answers here:
Access object child properties using a dot notation string [duplicate]
(13 answers)
Closed 3 years ago.
I know I'm missing something obvious here but say I have a JSON object that looks like this:
testObj = {
levelOne: {
levelTwo: []
}
}
I also have a string value:
var prop = 'levelOne.levelTwo';
I'm trying to determine if there's any way to basically do something like this:
var x = testObj[prop];
That doesn't work, but is there any way to do the equivalent?
There's no trivial way (e.g. testObj[prop]) of doing this, but the reduce function is well suited:
let nestedProp = (obj, path) =>
path.split('.').reduce((obj, prop) => obj[prop], obj);
let x = nestedProp({levelOne: {levelTwo: [5]}}, 'levelOne.levelTwo');
console.log(x);
You can use dynamic keys to access properties in an object but not multiple levels down.
i.e. You can do const a = testObject["levelOne"] but not what you tried. (Docs)
There are however helper libs that have functions to do this. One example is lodash.get function
This question already has answers here:
Where can I get info on the object parameter syntax for JavaScript functions?
(1 answer)
What does this symbol mean in JavaScript?
(1 answer)
Closed 5 years ago.
I am trying to understand some shorthand ways of writing ES6.
What I cannot fully understand in the example below is the last shorthand "({length})" - I comprehend that it does work, and that it gets the length property of the array, but not why. How could this syntax be applied in another scenario, not involving arrays?
//Declare array
var materials = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];
//Long version - ok
materials.map(function(material) {
return material.length;
});
//Arrow function - ok
materials.map((material) => {
return material.length;
});
//Shorthand arrow function - ok
materials.map(str => str.length);
//What? :)
materials.map( ({length}) => length );
The example above is from the mozilla documentation of arrow functions.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
The length is a property of strings, and can be destructured and returned in the map.
It's mostly the same as:
materials.map((str) => {
const {length} = str;
return length;
});
This question already has answers here:
Difference between Template literals and Tagged template literals?
(2 answers)
Closed 5 years ago.
Came across this javascript riddle on Twitter today: https://twitter.com/bradleymeck/status/890795540123865088
// #js
const a = f => f``;
const b = f => f``;
console.log(a(_ => _) === b(_ => _));
// what do you think this will/may print
At first glance it actually seems to make some decent sense. a is a function that takes some input f and then does f``. What f`` is a complete mystery to me so I tossed it into the console and received this input.
(()=>{console.log('hi')})``
hi
So it seems that a trailing template literal executes its preceding function. I understand that template literals are code that is executed immediately, but this behavior makes no sense to me. Can someone explain this to me?
Maybe this piece of code can help you:
var test1 = 2;
var test2 = 3;
function fTest(strings, ...params){
strings.forEach((x) => console.log(`string param: ${x}`));
params.forEach((x, index) => console.log(`param ${index}: ${x}`));
}
const a = (f, param1, param2) => f`tagged ${param1} template ${param2} literals`;
a(fTest, test1, test2);
That mistery is a tagged template literal:
essentially you're passing a template literals to your function, which will interpret the place holders as parameters, as well as the strings between them.
You can read here the documentation.
Another thing: if you want to ignore escape sequences you can use the raw function on the strings (see the example).