Assign options in destructure [duplicate] - javascript

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),
}));

Related

Print element inside array [duplicate]

This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Closed 2 years ago.
I have some problem to print elements inside array.
This is my Code
const mapStateToProps = state => {
console.log('antipasti', state.antipasti)
return { antipasti: state.antipasti };
};
const ConnectedList = ({ antipasti }) => (
<ul>
{
antipasti
.filter(antipasto => !!antipasto )
.map(antipasto => {
console.log('antipasto', antipasto);
<li>{antipasto.title}</li>
})
}
</ul>
);
const List = connect(mapStateToProps)(ConnectedList);
export default List;
What I would to obtain:
I would to print the element inside state.antipasti, I have used the filter to not consider the undefined or null elements.
This console.log('antipasto', antipasto); prints:
antipasto {title: "Prova"}title: "Prova"__proto__: Object
so I have thought to use antipasto.title to obtain the title, but nothing appears.
I have imported this page, in another parent page only with
{
antipasti
.filter(antipasto => !!antipasto )
.map(antipasto => {
console.log('antipasto', antipasto);
<li>{antipasto.title}</li>
})
}
When you do antipasto => { <li /> } like that, you're not actually RETURNING anything to your .map function. In general, the React structure looks more like this
{
antipasti
.filter(antipasto => !!antipasto )
.map(antipasto => (<li>{antipasto.title}</li>)
}
You may also be able to explicitly return inside the function, like Yury suggests in your comments, but that's not as common of a pattern and you'd only be doing it to support your console.log statement.

How to map data correctly before subscription?

I have following function:
this.localStorage.getItem('user').subscribe(user => {
this.user = user;
this.authSrv.getOrders(this.user.einsender).pipe(map(orders => {
map(order => { order["etz"] = "23"; return order})
return orders;
})).subscribe(orders => {
this.orders = orders;
this.completeOrders = orders;
console.log(orders);
this.waitUntilContentLoaded = true;
})
})
The result without the map is:
[{id: 1, etz: "21"}]
With the map from above I try to enter the array, then the order and in the order I try to change the etz property but somehow nothing changes. Can someone look over?
I appreciate any help!
I see multiple issues here.
Try to avoid nested subscriptions. Instead you could use one of the RxJS higher order mapping operators like switchMap. You could find differences b/n different higher order mapping operators here and here.
To adjust each element of the array you need to use Array#map method in addition to the RxJS map operator.
You could use JS spread operator to adjust some of the properties of the object and retain other properties.
Try the following
this.localStorage.getItem('user').pipe(
switchMap(user => {
this.user = user;
return this.authSrv.getOrders(this.user.einsender).pipe(
map(orders => orders.map(order => ({...order, order['etz']: '23'})))
});
})
).subscribe(
orders => {
this.orders = orders;
this.completeOrders = orders;
console.log(orders);
this.waitUntilContentLoaded = true;
},
error => {
// good practice to handle HTTP errors
}
);
map is an operator that goes in a pipe like this:
someObs$.pipe(map(arg => { return 'something'}));
You've done this:
someObs$.pipe(map(arg => {
map(arg => { return 'something' }) // this line here does nothing
return arg;
}));
It doesn't make any sense to use map inside the function you've given to map

what does ...var means on Array​.prototype​.map() [duplicate]

This question already has answers here:
What is destructuring assignment and its uses?
(3 answers)
Closed 3 years ago.
I'm fairly new at creating anonymous functions and using map, what does ...i mean on the following lines of code. tia
const airlines = this.state.airlines.map(i => (
{ ...i, editing : this.state.editing && i===item }
)
)
It's known as spread syntax, and in the current context it involves copying an object. It's the same as doing this:
const airlines = this.state.airlines.map(object => {
   object.editing = this.state.editing && object === item;
    return object;
});
So what we do is we create a shallow copy of the object, and we add properties to it. This is the purpose of spread syntax - to make a shallow copy, or to collect items for a shallow copy (known as rest syntax - collects the rest of the items). Here's a simplified example of spread syntax:
const arr = [{
name: "Jack"
}, {
name: "Joe"
}];    
const res = arr.map(e => ({ ...e,
age: Infinity
}));    
console.log(res);
.as-console-wrapper {
max-height: 100% !important;
top: auto;
}

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.

Return object from arrow function [duplicate]

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}

Categories

Resources