How to define the a [duplicate] - javascript

This question already has answers here:
Can `Array.find` use a default value if the callback function doesn't return anything truthy?
(2 answers)
Javascript: default value on missing property
(2 answers)
Closed 15 days ago.
module.exports.get = function (data) {
const _data = require("./data/Users.json");
if (_data.find(a => a.uid === data)) {
return a.name
} else return "User"
}
I want to return a.name but it says that a is not defined

The find method of array returns the first element that matches the provided condition; if no element is found, undefined is then returned. Thus:
const a = _data.find(user => user.uid === data)
if (a) {
  return a.name
} else {
  return "User"
}
It is recommended to give arguments and variables good names for better readability and maintainability. The following code can do the same thing, but is usually considered easier to understand:
module.exports.get = function (uid) {
  const users = require("./data/Users.json");
const user = users.find(user => user.uid === uid);
  return user?.name ?? "User";
}
The single question mark and double question marks are optional chaining operator and nullish coalescing operator respectively, which is not a must. Using if/else is perfectly fine in this case.

Related

Turning an array into array of objects but cannot run function [duplicate]

This question already has answers here:
Why can I not use the spread operator on a class function?
(3 answers)
Copy prototype for inheritance?
(2 answers)
Closed 25 days ago.
Alright, I must be missing something here. I have an object:
export class Country {
id: number = 0
name: string = ''
getNamePlusBob() {
return this.name + 'bob'
}
}
And I get the data from an API in an array, then pass it to the browser.
Once i have the data I want to turn the array into an array of objects of type 'Country'.
So I made this function (not sure if Hydrate is the correct term here?):
function hydrateArray(data, entity) {
let returnArray = []
console.log(data)
data.forEach((row) => {
const object = entity;
for (const [key, value] of Object.entries(row)) {
if(Object.hasOwn(object, key)) {
object[key] = value
} else {
console.log('Key not found in entity', key)
}
}
console.log(object.getNamePlusBob())
returnArray.push({...object})
})
return returnArray
}
const countries = hydrateArray(countryData, new Country())
In the console.log in the function, I can run the getNamePlusBob() and it returns the name plus bob. However, on the returned array countries, I cannot:
console.log(countries[0].getNamePlusBob())
TypeError: countries[0].getNamePlusBob is not a function
Why not? It was inside the hydrateArray function, why cant I run it outside?

Call a function according to its string name [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed last year.
I have a code which would be very repetitive, which according to the name of the string of an array executes one function or another.
I give an example of a code as I could do it.
// I use underscore in NodeJS
_.each(refresh, (value, key) => {
if(key === 'station') {
station.add({ id: value });
} else if(key === 'concentrator') {
concentrator.add({ id: value });
} else if....
});
It is possible to run the function according to your string to avoid so much checking with IF, etc.
[key].add({ id: value });
I have been watching several hours on the internet about the use of call, apply, etc; but I do not understand how it works well, perhaps because my knowledge of Javascript is not advanced.
Thanks !
Creating an anonymous function on an object is the best approach. As you can use the key to call the method.
Here is an example in code pen:
https://codepen.io/liam-hamblin/pen/KKyapNP
The code above takes in the key used to assign the function and does not require any checks. However, it is always the best approach to check that the key exists before calling.
const operations = {};
operations.add = (obj) => {
document.write("add - ");
document.write(JSON.stringify(obj));
}
operations.subtract = (obj) => {
document.write("subtract - ");
document.write(JSON.stringify(obj));
}
const input = prompt("Enter Function Name, type either subtract or add");
if (operations[input]) {
operations[input]({id:1});
} else {
document.write("no matching method")
}

Reduce method returns [duplicate]

This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Closed last year.
Why does the second assignment need return and the first returns variable total automatically?
const total = inventors.reduce(((total, inventor) => total += inventor.passed - inventor.born), 0);
const transportation = data.reduce(((prevVal, currentVal) => {
if (!prevVal[currentVal]) {
prevVal[currentVal] = 0;
}
prevVal[currentVal]++;
return prevVal;
}), {})
If return prevVal is omitted I get Uncaught TypeError: Cannot read properties of undefined
What is the difference in how reduce() acts with values. Is it effected by ternary operation? If so then why this returns 0?
const transportation = data.reduce(((prevVal, currentVal) =>
(!prevVal[currentVal]) ? prevVal[currentVal] = 0 : prevVal[currentVal]++), {})
When using curly braces with an arrow function, the return is not implicit, so you have to use return

Why this function is always returning null [duplicate]

This question already has answers here:
What does `return` keyword mean inside `forEach` function? [duplicate]
(2 answers)
Closed 2 years ago.
This is my JavaScript function to check if a particular entry exists or not in an array, but this is always returning null even though there is a match
function getSupplierForId(supplierId) {
data.suppliers.forEach(x => {
console.log('Current item id : ' + x.id);
console.log('Requested supplier id : ' + supplierId);
console.log('Both ids are equal : ' + (x.id === supplierId));
if (x.id === supplierId) {
console.log(x);
return x;
}
});
return null;
}
This is my console output:
Why is it returning null always?
Because you have return null; at the end. return statements do not cross function boundaries. return x; only returns from the inner function (whose caller is .forEach), not from the outer function.
Anyways, the right tool to use in your case is .find:
function getSupplierForId(supplierId) {
return data.suppliers.find(x => x.id === supplierId)
}
You might also find my post about callbacks interesting: https://felix-kling.de/blog/2019/javascript-callbacks-misconceptions.html

Differences between these 2 lines of code [duplicate]

This question already has answers here:
In Javascript, when is it necessary to assign a named function to a variable?
(3 answers)
Closed 6 years ago.
I'm learning some more ES6:
const _findCartItem = ( item ) => {
return _cartItems.find( cartItem => cartItem.id === item.id);
};
converts to:
var _findCartItem = function _findCartItem(item){
return _cartItems.find(function(cartItem){
return cartItem.id == item.id;
})
};
However, is there a difference between this and the following? Is this dual declaration necessary?
var _findCartItem = function(item){
return _cartItems.find(function(cartItem){
return cartItem.id == item.id;
})
};
Conceitualy, no, both will do the same. Syntactically, yes. First one is passing a reference of a named function to a variable, second a anonymous function.
Using first option is prefereble because you get better call stacks.

Categories