Mapping JavaScript Object Into An Array Of Hashes [duplicate] - javascript

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.

Related

update object value of all objects in javascript array with eslint error

I have a javascript array like this:
const arr=[{name:"Test", sex:"Male"},{name:"Test2",sex:"Female"},
{name:"Test3",sex:"Male"}
]
I want to change name of all the objects in the arr to "common" like this:
const arr=[
{name:"common",
sex:"Male"},
{name:"common",
sex:"Female"},
{name:"common",
sex:"Male"}]
What I am doing is:
arr.map((element) => {
element.name= "common";
return element;
});
using forEach:
arr.forEach((element) => {
element.name= "common";
return element;
});
This is working but giving a eslint warning stating:
no-param-reassign error
Assignment to property of function parameter 'element'.
How can I fix this without adding a skip for this? Maybe by using forEach or something else?Any leads will be highly appreciated.
You're not supposed to change the incoming parameters in a function to prevent unintended behaviors.
https://eslint.org/docs/rules/no-param-reassign
You can change turn off this rule or you can reassign the parameter to another variable:
arr = arr.map((element) => {
let e = element;
e.name = 'common';
return e;
});
Do like this:
const newArr = arr.map(element => ({ ...element, name: 'common' }));
const common = arr.map((item) => ({name: item.name = 'common', sex:
item.sex}))
console.log(common)
This is object array mapping. The syntax requires you use element/item and then I used dot notation. Just replace the first item element with "common" and you're good to go!

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.

Convert object to array in Javascript / React

Using REST, I am retrieving an object(JSON format) which is to be converted to an array so that it can be inserted into a table.
This is done in the rendering function of React.
The input is updated every N minutes from the back-end.
How do I convert an object to an array?
I need only the values, not the keys, since the keys are already present as column values beforehand in the table itself.
You can use Object#values (ECMAScript 2017), but it's not supported by IE (see browser's compatibility).
Note: The ECMAScript 6 specification defines in which order the properties of an object should be traversed. This blog post explains the details.
const map = { a: 1, b: 2, c: 3 };
const result = Object.values(map);
console.log(result);
If you need to support IE, you can use Object#keys with Array#map:
const map = { a: 1, b: 2, c: 3 };
const result = Object.keys(map).map((key) => map[key]);
console.log(result);
I am not sure by map you mean the Map object or an ordinary JS object. However, just for variety I would like to mention that the Map objects are mostly (probably always) stringified like JSON.stringify([...myMap]). So if you happen to receive a Map object in JSON data may be you should do something like;
var myMap = new Map().set(1,"hey").set(2,"you"),
mapData = JSON.stringify([...myMap]),
values = JSON.parse(mapData).map(d => d[1]);
console.log("mapData:",mapData);
console.log("values:",values);
You can set initial value as array firstly. See this example:
const [conversations, setConversations] = useState([]); // fianal data is array
useEffect(() => {
const fetchConversations = async () => {
const res = await axios.get("/conversations/" + user._id);
setConversations(res.data);
};
fetchConversations();
}, [user._id]);
res.data convert to array by using useState([]) as initial value and convert to object by using useState({}).
And
return(
{conversations.map((conv) => (
))}
)
You can set initial value as array firstly. See this example:
const [conversations, setConversations] = useState([]); // fianal data is array
useEffect(() => {
const fetchConversations = async () => {
const res = await axios.get("/conversations/" + user._id);
setConversations(res.data);
};
fetchConversations();
}, [user._id]);
res.data convert to array by using useState([]) as initial value and convert to object by using useState({}).
And map this array:
return (
<>
{conversations.map((conv) =>
(<Conversations key={conv._id} conversation={conv} />))}
</>
)

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