Conditional inside es6 .map - ecmascript-6

project im working on used es6/jsx and the airbnb linter but im having some trouble with the following code: i need to map items and compare it to another id but when i write it like this i get an error on the if statement, which is "parsing error unexpected token".
tried parentheses around the item, brackets after fat arrow, but not sure what the issue is. dont need to add return since it knows to expect it back. trying to find the way to get this working with the correct syntax.
const cartItems = items.map(item => {
if (id === item._id) {
console.log('found', item_id);
}
});
edit:
doing it like that, the .map(item has an error: expected parentheses around arrow function having curly braces.
moving over the => { i get an error: expected to return a value in arrow function
and in the console.log the item_id has a error: item._id is not defined, it should have been defined with the map but seems its not seeing it?
basically need to loop through the items id's and match them against another set of ids, if they match i need to combine the matching ones into a new variable

Ive changed it a bit, for what i need by doing it like this:
if (id === items.map(item => item._id)) {
this.setState({ inCart: true });
}
then just use the state value to conditionally load anything i needed.

Related

How to work with data returned by mysql select query in nodejs

I am working on a discord bot written in nodejs, the bot utilises a mysql database server to store information. The problem I have run into is that I cannot seem to retrieve the data from the database in a neat way, every single thing I try seems to run into some issue or another.
The select query returns an object called RowDataPacket. When googling every single result will reference this solution: Object.values(JSON.parse(JSON.stringify(rows)))
It postulates that I should get the values back, but I dont I get an array back that is as hard to work with as the rowdatapacket object.
This is a snippet of my code:
const kenneledMemberRolesTableName = 'kenneled_member_roles'
const kenneledMemberKey = 'kenneled_member'
const kenneledMemberRoleKey = 'kenneled_member_role_id'
const kenneledStaffMemberKey = 'kenneled_staff_member'
const kenneledDateKey = 'kenneled_date'
const kenneledReturnableRoleKey = 'kenneled_role_can_be_returned'
async function findKenneledMemberRoles(kenneledMemberId) {
let sql = `SELECT CAST(${kenneledMemberRoleKey} AS Char) FROM ${kenneledMemberRolesTableName} WHERE ${kenneledMemberKey} = ${kenneledMemberId}`
let rows = await databaseAccessor.runQuery(sql)
let result = JSON.parse(JSON.stringify(rows)).map(row => {
return row.kenneled_member_role_id
})
return result
}
This seemed to work, until I had to do a type conversion on the value, now the dot notations requires me to reference row.CAST(kenneled_member_role_id AS Char), this cannot work, and I have found no other way to retrieve the data than through dot notation. I swear there must be a better way to work with mysql rowdatapackets but the solution eludes me
I figured out something that works, however I still feel like this is an inelegant solution, I would love to hear from others if I am misunderstanding how to work with mysql code in nodejs, or if this is just a consequence of the library:
let result = JSON.parse(JSON.stringify(rows)).map(row => {
return row[`CAST(${kenneledMemberRoleKey} AS CHAR)`];
})
So what I did is I access the value through brackets instead of dot notation, this seems to work, and at least makes me able to store part of or the whole expression in a constant variable, hiding the ugliness.

How to satisfy the lint rules 'array-callback-return'?

This is my first cut:
const planLimits = {plan1: {condition1: 50, ...}}
function initialisePlanLimits(planLimits) {
const limits = new Map();
Object.keys(planLimits).map((planId) => (
const limitMap = new Map(Object.entries(planLimits[planId]));
limits.set(planId, limitMap);
));
return limits;
}
The linter flags this error: error Expected to return a value in this function array-callback-return
So I changed to this version:
function initialisePlanLimits(planLimits) {
const limits = new Map();
Object.keys(planLimits).map((planId) => (
limits.set(planId, new Map(Object.entries(planLimits[planId])))
));
return limits;
}
It throws another error Unexpected parentheses around single function argument having a body with no curly braces arrow-parens
My questions:
1) I reckon I can fix my first version by sticking in a return null within the curry bracket. But is there a better, more elegant way? A bogus return statement does not make sense in this context
2) Why the second version fails? Isn't it equivalent to the first version?
If I use forEach instead of map, it will not cause the array-callback-return lint error
Object.keys(planLimits).forEach((planId) => (
const limitMap = new Map(Object.entries(planLimits[planId]));
limits.set(planId, limitMap);
));
Well, accepted answer advocates about using 'forEach,' which is true. Please read below explaination from ESLint documentation,
Array has several methods for filtering, mapping, and folding. If we forget to write return statement in a callback of those, it's probably a mistake. If you don't want to use a return or don't need the returned results, consider using .forEach instead.
TLDR: ESLint and Function Return Values
This issue is caused by not returning a value when using map(), see how the results are expected according to the docs...
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. (Source: MDN WebDocs.)
Demonstration of Issue in JavaScript
With this code sample of JS, which shows a group of elements...
var newarray = [];
array.map( (item, index) => {
newarray.push('<li>' + item + '</li>');
});
I get this error...
Expected to return a value in arrow function array-callback-return
The error goes away if I add a single return to the above function, like so :
var newarray = array.map( (item, index) => {
return '<li>' + item + '</li>';
});
`map()` - So why should I use it?
You can clearly see elsewhere, too, on MDN Docs, that what is returned is, "A new array with each element being the result of the [return value of the] callback function." So, if you are using map(), it's also a very good idea to also use return returnvalue!
map() is a powerful tool. Don't throw that tool away.

Getting an error, text.match error when no results exist

I have code that looks like this
if (consearch.text.match(/kau$/).length >= 0)
{
trace("test");
}
which works fine if consearch.text value ends with "kau"
unfortunately when it does not end with "kau" I get a 1009 error
Am I missing something?? Not sure why its giving me this error
If you dont know how to use packages then use it like this, this is part of the code link #DodgerThud suggests,
function endsWith(input:String, suffix:String):Boolean {
return (suffix == input.substring(input.length - suffix.length));
}
if (endsWith(consearch.text,"kau"))
{
trace("test");
}
I know that you got an answer, but I'll try to explain why you got that error ?
So you got that error because String.match() returns an array ONLY if there is at least one substring in the string (consearch.text) that matches the specified pattern (/kau$/) otherwise it's returning null, and that's why that error is fired when your text didn't contain kau at its end.
If you want always to use RegExp, you can do it like this for example :
if (/kau$/.test(consearch.text))
{
trace('test');
}
Hope that can help.

How to use Transactions in cakephp

I write this code, but its not working, it gives this error
Call to a member function commit() on a non-object
Hear is my code
$datasource = $this->Arrear->getDataSource();
$datasource->begin();
if($this->Customar->saveField("total_bake",$amount) && $this->Arrear->save()){
$dataSource->commit();
return $this->redirect(array('action'=>'index'));
}else{
$dataSource->rollback();
$this->Session->setFlash('Data insert Failed','failure');
}
Variables in php(and hence in cakephp as well) are case-sensitive
http://php.net/manual/en/language.variables.basics.php
you have in your first line
$datasource = $this->Arrear->getDataSource();
but you are committing like
$dataSource->commit();
you have the data source assigned to $datasource, but not to $dataSource. The last variable even is not defined, that is why it is showing that error. So, you have to be sure you are using exactly the same variable (with same capitalization) in all places.

How to access json value inside reduce function in couchbase?

my reduce function in Couchbase[just for testing] :
function(keys,values,reduce){
return values[0];
}
The result is here
{"rows":[
{"key":null,"value":{"doctype":"closed_auctions","buyer":"person14108"}}
]
}
I would like to get individual value inside reduce for further process so when I try to get value of doctype like values[0].doctype it returns null even though there should be "closed_auctions". what is the problem? How can I get individual value(I mean field value) inside reduce function.
Your reduce function called after map performed. Also remember that re-reduce also called and at that time your result is further aggregated. You should use "group=true" when running this view.
So, sometimes values[0] might not have document
You need to check for existence of the property/doc first, e.g.
function(keys, values, rereduce)
{
if (values[0] && values[0].doctype)
{
return values[0].doctype;
}
}
Hope that helps.
See also: 9.5.2.4. Writing Custom Reduce Functions