Return object from arrow function [duplicate] - javascript

This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 7 years ago.
I want to output object from arrow function (in a short form), so full code is:
somemethod(function(item) {
return {id: item.id};
})
with arrow functions it's:
somemethod((item) => {
return {id: item.id};
})
and now short form should be something like:
somemethod(item = > {id: item.id} )
that does not work, as well as this one:
somemethod(item = > {{id: item.id}} )
only one solution I found for now is to use create Object notation:
somemethod(item = > new Object({id: item.id}) )
is there another way?

For Objects you have wrap your object using parentheses or else it doesn't work
This is because the code inside braces ({}) is parsed as a sequence of statements
Try as below
var func = () => ({ foo: 1 });
refer : arrow functions

somemethod(item => ({ id: item.id }))
Test:
> a = item => ({id: item.id})
< function item => ({id: item.id})
> a({ id: 5, name: 7 });
< Object {id: 5}

Related

array.find returning undefined JavaScript (Express.js) [duplicate]

This question already has an answer here:
Why doesn't my arrow function return a value?
(1 answer)
Closed last month.
Hi
Hi! Thanks in advance for your answer, today I was creating a method for my class with name findOne, I'm using an arrow function with the method .find, but is going to return undefined if my code is like the next one:
findOne(id) { return this.products.find((item) => {item.id === id}); }
But is going to work if I don't use the brackets "{}":
findOne(id) { return this.products.find((item) => item.id === id); }
I thought that it was along the same lines, so I want to ask this community.
Thanks!
I resolved already my issue, but I want to know why is happening
let obj = [{
id: 1,
name: 'foo'
},
{
id: 2,
name: 'abc'
},
{
id: 3,
name: 'foo1'
}
];
function findOne(id) {
return obj.find((item) => {
return item.id === id
});
}
console.log(findOne(2));

javascript finding a key in nested object [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
How to find object in array by property in javascript?
(3 answers)
Closed 4 months ago.
I have an object called _test shaped in the below form where the first element is id and the second is name:
"_test": [
{id:1, name:andy},{id:2, name:james}, {id:3, name:mike}
]
I then have another field called key. the values that key takes on can equal values of id in the subs
key
I currently use
_test.flatMap( c => c.id).find(elem => elem == key) || null
How can I get this to return the name? I'm at a loss and having a major brain fart.
You can find the name for a given id via:
const
_test = [
{ id: 1, name: 'Andy' },
{ id: 2, name: 'James' },
{ id: 3, name: 'Mike' }
],
key = 2,
{ name } = _test.find(({ id }) => id === key) ?? {};
console.log(name); // James
actually is pretty easy, you just need to use find on your array, it takes a function as an argument.
pd: when doing ([id, name]) I'm destructuring the array, you can change that to:
names.find(entry => key === entry[0])
const names = [
[1, 'andy'],
[2, 'james'],
[3, 'mike']
];
const key = 3;
const solution = names.find(([id, name]) => key === id)
console.log("solution => ", solution)
console.log("just the name => ",
solution[1]);

Assign options in destructure [duplicate]

This question already has an answer here:
How to return a spread operator in a map arrow function in one line [duplicate]
(1 answer)
Closed 2 years ago.
I've tried to rewrite the following code according to ES6. I keep getting ESLint warnings, and I've spent about 20 minutes on it so far, I'm not quite sure how to write it...
.then(result => {
const [categories, properties, placements] = result.map(r => r.data);
this.properties = properties.map(property => {
{
...property,
category: categories.find(c => c.id === property.category_id),
property: placements.filter(p => p.property_id === property.id),
}
});
});
The code above just doesn't parse at all, but depending on what I've tried it says I can't use return {} in an arrow function.
If I try to just modify the argument I get an error to no-param-reassign
I realized I can run eslint fix to see how it would be done:
this.properties = properties.map(property => ({
...property,
category: categories.find(c => c.id === property.category_id),
property: placements.filter(p => p.property_id === property.id),
}));

JS - Destructuring by picking only what you need [duplicate]

This question already has answers here:
Is it possible to destructure onto an existing object? (Javascript ES6)
(16 answers)
ES2015 deconstructing into an object [duplicate]
(1 answer)
How to get a subset of a javascript object's properties
(36 answers)
Closed 4 years ago.
I'm trying to understand ES6, specifically destructuring feature.
How can I translate these lines using destructuring?
const user = {...}
const sessionData = ({
session_id: user.session_id,
selector: user.selector,
validator: user.validator
})
I tried
const sessionData = {session_id, selector, validator} = user
But it raises a syntax error, because of course destructuring is for giving a certain variable a value from an object but I don't understand how to do something like this with an object
Use
const { session_id, selector, validator } = user;
Then
const sessionData = { session_id, selector, validator };
You could also do it like so (using anonymous functions)
const user = { session_id: 1, selector: "my-selector", validator: 1, unused: 3 };
const session = (({ session_id, selector, validator }) => ({ session_id, selector, validator }))(user);
console.log(session);
You can use a function to create the new object with the fields you want.
const original = { a: 1, b: 2, c: 3 };
const pick = (o, fields) => fields.reduce((acc, key) => {
acc[key] = o[key];
return acc;
}, {});
console.log(pick(original, ['a', 'b']));
Or use the comma operator to destructure and assign.
const original = { a: 1, b: 2, c: 3 };
const newone = ({ a, b } = original, { a, b });
console.log(newone);
But keep in mind that the comma operator creates global variables, if the variables to assign the destructure are not declared. Hope this helps.

Mapping JavaScript Object Into An Array Of Hashes [duplicate]

This question already has an answer here:
'Unexpected token' syntax error in object returned by arrow function [duplicate]
(1 answer)
Closed 4 years ago.
I want to take a Javascript object and convert it into an array of hashes.
The following works to get just one element of the object and turn it into an array:
const coordinatesArray = items.map((item) => item.latitude)
Returns: [51.5165328979492, 51.5990409851074, 51.5990409851074, 51.5165328979492, 51.5098190307617, 51.5128326416016, 51.5098190307617, 51.501766204834, 51.514087677002, 51.4983825683594, 51.5294952392578, 51.5123977661133, 51.5011863708496, 51.5204887390137, 51.514087677002, 51.5117797851562, 51.5139465332031]
But when I try to create hash elements to make up the array, I get an error:
const coordinatesArray = items.map((item) => { x:item.latitude, y:item.longitude })
Returns: Uncaught Error: Module build failed: SyntaxError: Unexpected token, expected ;
What am I doing wrong?
Try the following:
const coordinatesArray = items.map((item) => ({ x:item.latitude, y:item.longitude }))
Lambda functions returning objects need an extra bracket set () to distinguish them from a function body.
You need some parenthesis around the curly brackes, otherwise it is interpreted as block statement in arrow functions.
const coordinatesArray = items.map((item) => ({ x: item.latitude, y: item.longitude }));
Shorter with destructuring and short properties:
const coordinatesArray = items.map(({ latitude: x, longitude: y }) => ({ x, y }));
Parenthesize the body of function to return an object literal expression:
params => ({foo: bar})
In your case:
const coordinatesArray = items.map((item) => ({ x:item.latitude, y:item.longitude }))
More Info here.

Categories

Resources