I'm using the map function to assign and populate table names only if object['Size/ scale of support']. is equal to a data that I'm passing using props. I've seemed to have got the logic right but the map is not allowing me to use my if statement. Is there a way I can use an if statement on my map function?
updateData(result) {
const data = result.data;
console.log(data);
let new_data = []
data.map(
(object) => {
if (object['Size/ scale of support'].toLowerCase() === this.props.data.toLowerCase()) {
console.log("support",object['Size/ scale of support'])
new_data.push(
{
scale_of_support : object['Size/ scale of support'],
size_of_funding_instrument : object['Size of funding instrument'],
maturity_of_innovation_candidate : object['Maturity of innovation/ candidate'],
maturity_of_innovation_innovator : object['Maturity of innovation/ innovator'],
web_and_profile : object['Web and profile'],
source_of_information : object['Source of information'],
funding_instrument_name : object['Funding instrument name'],
}
)
}
}
)
this.setState({ cvs: new_data });
}
This code works:
var foo = [1,2,3];
foo.map(item => {
if (item === 2) console.log(item * 2);
return item;
});
which proves that your code is correct. If you use Typescript/Lint, then you may encounter errors because of this. If that's the case, you have several options to solve it:
Refactor
You can refactor your code, write a function that performs the conditional and its operation and only call that function from inside map.
Ternary operator
You may use the ternary operator as well, like:
mycondition ? myFunction() : myOtherValue;
Related
I hope you are all well 🙂
I would like to ask something that (I hope) is basic, i have this function that is responsible for returning the filtered objects with a specific "key" variable that translates to color or size.
Well I put the color and size variables inside an array of objects, I would like to know what is the terminology I have to use now in my "item[key]" to be able to get to my "color" variable as shown in the last picture 😦
picture showing what key im able to get now and then what key im looking to get!
Thanks in advance for any and all help, have a nice day!
here is the code for the two functions used in this process:
const [filtros,setFiltros] = useState({});
const gerirFiltros = (evento) =>{
const valor = evento.target.value;
console.log(evento.target.name + evento.target.value)
if (evento.target.name === "cor" ) {
const cor = evento.target.name
setFiltros( {
...filtros,
["variacoes"]:[{
[evento.target.name]:valor
}],
})
}
else {
setFiltros({
...filtros,
[evento.target.name]:valor,
}) // THIS IS JUST TO PASS TO PAGE #2 (https://pastebin.com/4GH3Mi3H) THE VARIABLE `filtros` THAT IS AN ARRAY WITH MANY FILTERS LIKE -> {marca:"Paz rodrigues"}, etc..
And the functio that receives the filter ( the one i think i need to change) :
useEffect(() => {
categoria &&
setProdutosFiltrados(
produtos.filter((item) =>
Object.entries(filtros).every(([key,value],i) =>
//console.log("key ->" + key + "value->" + value[0].cor) )
item[key].includes(value)
)
)
)
You can use some()
useEffect(() => {
categoria &&
setProdutosFiltrados(
produtos.filter((item) =>
Object.entries(filtros).every(([key,value],i) =>{
//Here the value is an array 'variacoes' so to check colors use filter to get all the elements of 'variacoes' array;
//Also assuming that the color you are passing will be available here as item[key]
var allColors = item.map(i=>i.cor)
return value.some((val)=>allColors.includes(val.cor))
}
)
)
)
I want to show the top 3 result via .slice function.
How to do that after filter function
I have tried to add .slice after the match in filter function, but it's didn't work properly
Below is the code
filteredEntitySearch () {
let entity = this.options
return entity.filter((entity) => {
return entity.name.match(this.searchQuery).slice(0, 4)
})
},
For some context the main function (filteredEntitySearch) is designed for
get all the match entity with the search query (searchQuery)
show the 3 top result
Thanks for the help!
Your have made several mistakes.
filter function parameter name should not be same with array name for better understanding
slice function used in wrong place
slice parameter should be slice(0, 3) if you want 3 result
Your code should be like this:
filteredEntitySearch () {
let entities = this.options
return entities.filter((entity) => {
return entity.name.match(this.searchQuery)
}).slice(0, 3)
},
Move it outside of your filter:
filteredEntitySearch () {
let entity = this.options
return entity.filter((entity) => {
return entity.name.match(this.searchQuery);
}).slice(0, 3);
}
Here you get results after filter(17 elements) but only the top 3 are shown
var arr=[1,2,3,4,5,6,7,6,5,6,5,5,5,4,4,3,3,22,2,2,1,1,4,5,6,77]
console.log(arr.filter(e=>e>3).slice(0,3))
In my ReactJS application I am getting the mobile numbers as a string which I need to break and generate a link for them to be clickable on the mobile devices. But, instead I am getting [object Object], [object Object] as an output, whereas it should be xxxxx, xxxxx, ....
Also, I need to move this mobileNumbers function to a separate location where it can be accessed via multiple components.
For example: Currently this code is located in the Footer component and this code is also need on the Contact Us component.
...
function isEmpty(value) {
return ((value === undefined) || (value === null))
? ''
: value;
};
function mobileNumbers(value) {
const returning = [];
if(isEmpty(value))
{
var data = value.split(',');
data.map((number, index) => {
var trimed = number.trim();
returning.push(<NavLink to={`tel:${trimed}`} key={index}>{trimed}</NavLink>);
});
return returning.join(', ');
}
return '';
};
...
What am I doing wrong here?
Is there any way to create a separate file for the common constants / functions like this to be accessed when needed?
First question:
What am I doing wrong here?
The issue what you have is happening because of Array.prototype.join(). If creates a string at the end of the day. From the documentation:
The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
Think about the following:
const navLinks = [{link:'randomlink'}, {link:'randomlink2'}];
console.log(navLinks.join(','))
If you would like to use concatenate with , then you can do similarly like this:
function mobileNumbers(value) {
if(isEmpty(value)) {
const data = value.split(',');
return data.map((number, index) => {
const trimed = number.trim();
return <NavLink to={`tel:${trimed}`} key={index}>{trimed}</NavLink>;
}).reduce((prev, curr) => [prev, ', ', curr]);
}
return [];
};
Then you need to use map() in JSX to make it work.
Second question:
Is there any way to create a separate file for the common constants / functions like this to be accessed when needed?
Usually what I do for constants is that I create in the src folder a file called Consts.js and put there as the following:
export default {
AppLogo: 'assets/logo_large.jpg',
AppTitle: 'Some app name',
RunFunction: function() { console.log(`I'm running`) }
}
Then simply import in a component when something is needed like:
import Consts from './Consts';
And using in render for example:
return <>
<h1>{Consts.AppTitle}</h1>
</>
Similarly you can call functions as well.
+1 suggestion:
Array.prototype.map() returns an array so you don't need to create one as you did earlier. From the documentation:
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
I hope this helps!
Update: scroll to see my solution, can it be improved?
So I have this issue, I am building a word translator thats translates english to 'doggo', I have built this in vanilla JS but would like to do it React.
My object comes from firebase like this
dictionary = [
0: {
name: "paws",
paws: ["stumps", "toes beans"]
}
1: {
name: "fur",
fur: ["floof"]
}
2: {
name: "what"
what: ["wut"]
}
]
I then convert it to this format for easier access:
dictionary = {
what : ["wut"],
paws : ["stumps", "toe beans"],
fur : ["floof"]
}
Then, I have two text-area inputs one of which takes input and I would like the other one to output the corresponding translation. Currently I am just logging it to the console.
This works fine to output the array of the corresponding word, next I have another variable which I call 'levelOfDerp' which is basically a number between 0 - 2 (set to 0 by default) which I can throw on the end of the console.log() as follows to correspond to the word within the array that gets output.
dictionary.map(item => {
console.log(item[evt.target.value][levelOfDerp]);
});
When I do this I get a "TypeError: Cannot read property '0' of undefined". I am trying to figure out how to get past this error and perform the translation in real-time as the user types.
Here is the code from the vanilla js which performs the translation on a click event and everything at once. Not what I am trying to achieve here but I added it for clarity.
function convertText(event) {
event.preventDefault();
let text = inputForm.value.toLowerCase().trim();
let array = text.split(/,?\s+/);
array.forEach(word => {
if (dictionary[word] === undefined) {
outputForm.innerHTML += `${word} `;
noTranslationArr.push(word);
} else {
let output = dictionary[word][levelOfDerp];
if (output === undefined) {
output = dictionary[word][1];
if (output === undefined) {
output = dictionary[word][0];
}
}
outputForm.innerHTML += `${output} `;
hashtagArr.push(output);
}
});
addData(noTranslationArr);
}
Also here is a link to the translator in vanilla js to get a better idea of the project https://darrencarlin.github.io/DoggoSpk/
Solution, but could be better..
I found a solution but I just feel this code is going against the reason to use react in the first place.. My main concern is that I am declaring variables to store strings inside of an array within the function (on every keystroke) which I haven't really done in React, I feel this is going against best practice?
translate = evt => {
// Converting the firebase object
const dict = this.state.dictionary;
let dictCopy = Object.assign(
{},
...dict.map(item => ({ [item["name"]]: item }))
);
let text = evt.target.value.toLowerCase().trim();
let textArr = text.split(/,?\s+/);
let translation = "";
textArr.forEach(word => {
if (dictCopy[word] === undefined) {
translation += `${word} `;
} else {
translation += dictCopy[word][word][this.state.derpLvl];
}
});
this.setState({ translation });
};
levelOfDerp is not defined, try to use 'levelOfDerp' as string with quotes.
let output = dictionary[word]['levelOfDerp' ];
The problem happens because setState() is asynchronous, so by the time it's executed your evt.target.value reference might not be there anymore. The solution is, as you stated, to store that reference into a variable.
Maybe consider writing another function that handles the object conversion and store it in a variable, because as is, you're doing the conversion everytime the user inputs something.
Consider the object:
var myObj = {
hugeKey1: 'xxx',
hugeKey2: 'xxx',
hugeKey3: 'xxx',
hugeKey4: 'xxx',
prettyKey1: 'Only one'
};
Following is the code for getting a list of all keys with pattern hugeKey:
var filteredKeySet = _.filter(
Object.keys(data),
function (key) {
if (key.match(/hugeKey/i)) {
return true;
}
}
);
There is only one key named PrettyKey1, but this the number at the end is dynamic - it could be PrettyKey2 as well.
What's the shortest piece of code to find the first key with pattern match?
Something that looks like Object.keys(myObj).findFirstMatch(/PrettyKey/i);
In addition to previous answers, in case you need to perform such operation frequently and the target object is also changing you could write following utility function:
function matchBy(pattern) {
return obj => Object.keys(obj).find(k => k.match(pattern));
}
or
function findBy(pattern) {
return obj => Object.keys(obj).find(k => k.includes(pattern));
}
And then use them as :
var match = matchBy(/prettyKey/i);
var find = findBy("prettyKey");
....
console.log(match(myObj));
console.log(find(myObj));
From
function callback(elm){
if(elm.match(/prettyKey/i)) return true;
}
Object.keys(myObj).findIndex(callback);
to
Object.keys(myObj).findIndex(key=>key.match(/PrettyKey/i))
or
Object.keys(myObj).findIndex(key=>key.includes('prettyKey'))
According to your requirements, this is probably what you need:
const firstMatchedKeyNameInObject = Object.keys(myObj).find(keyName => keyName.includes('prettyKey'));
Ok so found a possible answer almost immediately after posting:
Object.keys(myObj).findIndex(x=>x.match(/PrettyKey/i))
Just needed to use the => based index search on the keys.
Wonder if there is a faster way of doing this via lodash.