I have a little problem with filtering my array.
I want display a product filtered by input value with a name or platform or something other value. With name is no problem, but i don't know how to do it with platforms.
Bottom is my logic and file with products, txh very much for help
live: live
repo: repo
const [inputText, setInputText] = useState('')
const inputHandler = e => {
const text = e.target.value.toLowerCase()
setInputText(text)
}
const filteredData = PRODUCT_LIST.filter(el => {
if (inputText === '') {
return
} else {
return el.name.toLowerCase().includes(inputText)
}
})
const PRODUCT_LIST = [
{
id: 'gow',
name: 'God of War',
developer: 'Santa Monica Studio',
category: 'games',
platform: 'PlayStation 4',
version: 'PL',
price: 39,
},]
You need to make a conditional check.
First, check whether the search text matches the name; if it fits, return the list. If not, then check whether it matches the platform.
const filteredData = PRODUCT_LIST.filter(el => {
const findByName = el?.name?.toLowerCase().includes(inputText);
const findByPlatform = el?.platform?.toLowerCase().includes(inputText);
if (inputText === '') {
return
} else {
return findByName || findByPlatform
}
})
You should do something like this just return true when you are getting empty string. Let me know if it works.
const filteredData = PRODUCT_LIST.filter(el => {
if (inputText === '') {
return true;
} else {
return (el.name.toLowerCase().includes(inputText.toLowerCase()) || el.platform.toLowerCase().includes(inputText.toLowerCase()))
}
})
Related
my course is telling me this is the solution to checking if contacts already has {name} in it.
useEffect(() => {
const nameIsDuplicate = () => {
const found = contacts.find((contact) => contact.name === name);
if (found !== undefined) {
return true;
}
return false;
};
if (nameIsDuplicate()) {
setDuplicate(true);
} else {
setDuplicate(false);
}
}, [name, contacts, duplicate]);
Does my code do the same thing?
useEffect(() => {
if (contacts.includes(name)) {
setDuplicate(true)
} else {
setDuplicate(false)
}
}, [name, contacts, duplicate]);
No, contact seems to be a list, like:
[
{name: "Mario"},
{name: "Andrea"},
...
]
I guess this given the predicate for the find method:
contact.name === name
In the second example it is using the includes passing the same name variable that seems to indicate a string, so in the second snippet contacts.includes will be always false
I have a problem trying to update an Array of Objects that lives in a Themecontext, my problem is with mutation, I'm using Update from Immutability helpers. the thing is that when I update my array in my specific element, This appears at the end of my object.
This is my code:
function changeValueOfReference(id, ref, newValue) {
const namevalue = ref === 'colors.primary' ? newValue : '#';
console.warn(id);
const data = editor;
const commentIndex = data.findIndex(function(c) {
return c.id === id;
});
const updatedComment = update(data[commentIndex], {styles: { value: {$set: namevalue} } })
var newData = update(data, {
$splice: [[commentIndex, 1, updatedComment]]
});
setEditor(newData);
this is my result:
NOTE: before I tried to implement the following code, but this mutates the final array and break down my test:
setEditor( prevState => (
prevState.map( propStyle => propStyle.styles.map( eachItem => eachItem.ref === ref ? {...eachItem, value: namevalue}: eachItem ))
))
Well, I finally understood the issue:
1 - commentIndex always referenced to 0
The solution that worked fine for me:
1 - Find the index for the Parent
2 - Find the index for the child
3 - Add an array []
styles : { value: {$set: namevalue} } => styles :[ { value: [{$set: namevalue}] } ]
Any other approach is Wellcome
Complete Code :
function changeValueOfReference(id, referenceName, newValue) {
const data = [...editor];
const elemIndex = data.findIndex((res) => res.id === id);
const indexItems = data
.filter((res) => res.id === id)
.map((re) => re.styles.findIndex((fil) => fil.ref === referenceName));
const updateItem = update(data[elemIndex], {
styles: {
[indexItems]: {
value: { $set: namevalue },
variableref: { $set: [''] },
},
},
});
const newData = update(data, {
$splice: [[elemIndex, 1, updateItem]],
});
setEditor(newData);
}
I want to add an All Option to my existing select box.
Select box is creating with some API data. With the API data set I want to add an ALL option above.
This is my code.
const useChemicals = () => {
const [data, setData]: any = useState([]);
useEffect(() => {
const getChemicalsData = async () => {
try {
const results = await searchApi.requestChemicalsList();
if (results.data) {
let groupCount = 0;
const chemList: any = [];
results.data.data.chemicals.map((chemical: any, index: number) => {
if (chemical.key === '') {
chemList.push({
label: chemical.value,
options: [],
});
}
});
results.data.data.chemicals.map((chemical: any, index: number) => {
if (chemical.key === '') {
if (index > 1) {
groupCount += 1;
}
} else {
chemList[groupCount].options.push({
label: chemical.value,
value: chemical.key,
});
}
});
setData([...chemList]);
}
} catch (e) {}
};
getChemicalsData();
}, []);
return data && data;
};
export default useChemicals;
How can I add this. Please help me, I am new to React.
I'm trying to update the input value on a form. The input value I need to update sits within an array of objects within another array of objects. I'm trying to update the address within emails (see below).
const userProfiles = [{
firstName: 'John',
emails: [{ address: 'john#gmail.com' }]
}]
Each keystroke updates the field and sate of the userProfiles, however, the input field disengages. So I have to keep reselecting the input field. What am I missing here?
handleInputChange = (userProfileId, index) => (event) => {
const target = event.target;
const value = target.value;
const name = target.name;
const userProfiles = this.state.userProfiles.map((userProfile) => {
if (userProfile._id === userProfileId) {
if (name === 'email') {
const emails = userProfile.emails.map((email, idx) => {
if (idx === index) {
return {
...email,
address: value,
};
}
return {
...email,
};
});
return {
...userProfile,
emails,
};
}
return {
...userProfile,
[name]: value,
};
}
return {
...userProfile,
};
});
this.setState({
userProfiles,
});
}
handleInputChange = (userProfileId, index) => (event) => {
const target = event.target;
const value = target.value;
const name = target.name;
let { userProfiles } = this.state;
userProfiles.map((eachProfile) => {
let { emails } = userProfiles.emails;
if (userProfile._id === userProfileId) {
if(name === 'email') {
emails.map((emails, idx) => {
if (idx === index) {
emails = value;
}
})
}
}
});
this.setState({
...this.state,
userProfiles
})
}
Can you try this one?
i have a object like
obj = {name:"xxx" , des1:"x",des2:"xx",des3:"xxx" , age:"12"}.
But the property of des can be incresed as des1,des2,des3,des4 ... according to the users inputs. So basically we don't know how much of "des" properties are there in the object.
I want do something like this. Grab all the properties of des and put them in array. Then update the object as follows
obj = {name:"xxx" , description:["x","xx","xxx"] , age:"12"}
how can I achieve this using ES6 syntax
you can transform your data in this way:
const transformed = Object.keys(obj).reduce(
(acc, key) => {
return key === 'name' || key === 'age'
? { ...acc, [key]: obj[key] }
: { ...acc, description: [...acc.description, obj[key]] }
},
{ description: [] }
)
What about this one?
const f = {name:"xxx", des1:"x", des2:"xx", des3:"xxx", age:"12"};
const { name, age, ...rest} = f;
const result = { name, age, description: Object.values(rest) };
console.log(result) // { name: 'xxx', age: '12', description: [ 'x', 'xx', 'xxx' ] }
You can make use of reduce and then match the string with the regex which checks if the string is des, followed by a number
var obj = {name:"xxx" , des1:"x",des2:"xx",des3:"xxx" , age:"12"}
const res = Object.keys(obj).reduce((acc, key)=> {
if(key.match(/^des([0-9]+)$/)) {
if(acc.description) {
acc.description.push(obj[key]);
} else {
acc.description = [obj[key]];
}
} else {
acc[key] = obj[key];
}
return acc;
}, {})
console.log(res);