I am trying to make an app(IOS and Android) for ads and I want to be able to go into the objects of my ads and identify a boolean and if it is true do one thing and something else otherwise.
Here are the objects of an ad:
I want to go into the object and if the "ReceiveHelp" is true i want the code to execute say blue as backgroundcoulor otherwise red. The problem is I don't know how to go into the object and identify the boolean props only.
export const publicAdFetch = () => {
return (dispatch) => {
firebase.database().ref('/users').once('value').then((snapshot) => {
const usersData = snapshot.val();
let sortedAdds = Object.keys(usersData).reduce((prev, userId) => {
let ads = usersData[userId].ads;
ads = Object.keys(ads).map(key => {
return { ...ads[key], id: key };
});
return prev.concat(ads);
}, [])
.sort((a, b) => (b.time - a.time));
this is the code I currently have to put everything into an array and then sort by time. But I have no idea how to just see if the boolean is true or false
You can check for a boolean with typeof
const yourObjArray = [
{desc: "fdf", price: "rrr", receiveHelp: true},
{desc: "ccc", price: "254", receiveHelp: 351},
{desc: "aaa", price: "gdg", receiveHelp: false},
{desc: "aaa", price: "gdg", receiveHelp: "charlie"},
{desc: "feee", price: "jth", receiveHelp: true},
];
yourObjArray.forEach(obj => console.log("The type is: ", typeof obj.receiveHelp));
Once you know if the receiveHelp is a boolean you can check for true or false easily with if():
const receiveHelp = true;
if (typeof receiveHelp === 'boolean') {
if (receiveHelp) { // This equals to if (receiveHelp === true)
console.log("this is true: ", receiveHelp);
} else { // else false
console.log("this is false: ", receiveHelp);
}
}
Thanks #Rodius
You're help gave me some inspiration!
I solved it but doing:
let iftrue = '#666';
if (this.props.callbackFromParent.receiveHelp) {
iftrue = '#ff0';
and then in my styles for the ad i had "iftrue", didn't realize it was so simple that ".receiveHelp" was enough to go into the object to check on the values.
Related
I have this variable in my environment.ts:
featureToggle: {"feature1": true, "feature2: false}
In a service of mine, I want to give these values to a component with a getAll-method, just like:
getAll() {
return environment.featureToggle;
}
In a component I'm having an array and call the servicemethod in my ngOnInit, where I assign the values to my array. Through *ngFor im iterating through the array.
Then I get an ERROR NG0901 IterableDiffers.find.
Yes, it might be, because it is an Object Array, so I would have to convert it in my service first to a normal Array, or assign the values to an interface to work with it?
like
interface FeatureInterface {
feature: string,
isActive: boolean;
}
But I can't even .map through my environments variable nor does forEach work. I also tried Object.keys(environment.featureToggle). Is there any way to access and iterate my properties in my environment.ts and work with them in any component?
Component:
features: FeatureInterface[] = [];
ngOnInit(): void {
this.features = this.featureToggleService.getAllFeatures()
Html:
<div *ngFor="let item of features">
{{item.feature}}
...
Check this out!
let featureToggle = { "feature1": true, "feature2": false, "feature3": true};
const result = Object.entries(featureToggle).filter((e) => e[1]).map((i) => i[0]);
console.log(result);
UPDATE 1:
Based on the requirement(as mentioned in the comments), try this:
let featureToggle = { "feature1": true, "feature2": false, "feature3": true };
const result = Object.entries(featureToggle).map((i) => {
return {
feature: i[0],
isAvailable: i[1]
}
});
console.log(result);
[ { feature: 'feature1', isAvailable: true },
{ feature: 'feature2', isAvailable: false },
{ feature: 'feature3', isAvailable: true } ]
So I'm using mongodb to fetch some data from the database.
The issue is when I try to check for something in an array
Here is what the structure looks like:
Example array structure
{ // ...
likedPeople: [
{
name: "foo"
image: "test",
},
{
name: "bar",
image: "baz",
}
]
}
This is the array i get Back.
So when i try to find if it includes a certain value,
eg:
const displayName = "foo";
console.log(
likedPeople.map((likedPerson) => {
return likedPerson.name === displayName; // Output: [true, false]
})
);
But then If i again try to do some other method on it like map() or includes(), It breaks the setup:
const response = likedPerson.name === displayName; // Output: [true, false]
response.map((res) => console.log(res)); // Output: ERROR: response.map() is not a function
But the fact is that I am getting an array with the values, so what am I even doing wrong here?
I tried adding an optional chaining response?.map() but still it gave me the same error.
Also the includes() method also returns me the same response.includes is not a function error.
Can anyone help?
Use the some method to check the name exists in likedPeople :
const likedPeople = [
{
name: "foo",
image: "test",
},
{
name: "bar",
image: "baz",
}
];
const displayName = "foo";
const isExist = likedPeople.some(people => people.name === displayName);
console.log(isExist)
I have a problem with a dynamic state I am setting. My first state looks like this:
const [exercises, setExercises] = useState([{
id: 123,
title: "Title here",
category: "someCategory"
}])
A user then selects an item of this state. I create a second state representing the selected object, but adding additional properties to it. For instance I am adding and initializing the properties 'amount' and 'unit'.
const [selectedExercises, setSelectedExercises] = useState([{
id: 123,
title: "Title here",
category: "someCategory",
amount: 0,
unit: ''
}])
I want the user to choose amount and unit from a form. How do I access and change those two properties in the state? Since I don't know the user's selection, I have to find the object within the state first.
I have tried things like (el being called from an input element somewhere):
setSelectedExercises([
...selectedExercises,
(selectedExercises.find(exercise => exercise.title === el.title).amount = 1),
])
How do I find the object in question and update its amount property (for example in an onChange method)?
const [selectedExercises, setSelectedExercises] = useState([{
id: 123,
title: "Title here",
category: "someCategory",
amount: 0,
unit: ''
}]);
// Your handler should look like this and
// you should call handleAmountChange(el.id, 1)
function handleAmountChange(amount, id) {
setSelectedExercises(prev => prev.map(selectedExercise => {
if (selectedExercise.id === id) {
return {
...selectedExercise,
amount
}
}
return selectedExercise;
}));
}
A more generic function to change any property would look like this.
function handleChange(id, property, value) {
setSelectedExercises(prev => prev.map(selectedExercise => {
if (selectedExercise.id === id) {
return {
...selectedExercise,
[property]: value
}
}
return selectedExercise;
}));
}
I am going to Push some objects in an array and delete them according to there specific ID.
Now the challenge is that i wants to do the both push and delete using a single toggle button.
this.state = {
array: [{
id: 1,
name: "Abc",
checkBoxState: true
}, ]
}
handleData(label, value, id) {
let obj = JSON.stringify({
id: id,
name: label,
checkBoxState: value
});
let array = this.state.array;
array.push(obj);
console.log(array);
}
Please tell me the method how to make it possible on a single button.
For Example if i press ok button i will fetch the properties and push into an array and if i press again this button it will have to delete the object from array according to the ID.
Edit based on your comments. First check to see if the item exists in the array. If it does, delete it. If it does not add a new item. I don't have time to test but something like this may work.
this.state = {
array: [{
id: 1,
name: "Abc",
checkBoxState: true
}]
}
handleData(label, value, id) {
let array = this.state.array;
let arrayIds = Object.values
for (let item of array) {
if (item.id === id) {
let deletedObj = array.filter(item => item.id === id)
this.setState({
array: deletedObj,
})
return
}
}
let obj = JSON.stringify({
id: id,
name: label,
checkBoxState: value
});
array.push(obj);
this.setState({
array
})
}
}
console.log(this.state.array);
}
It is a tricky one. I thought I could use $in, but after querying, it wasn't where I was looking for.
This is my schema
var gameSchema = new mongoose.Schema({
state: {
type: String,
default: "invited"
},
finished: {
type: Boolean,
default: false
},
players: {
type: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'users'
}],
required: true,
},
scores: [scoreSchema],
chat : [chatSchema]
});
The request I'm trying to make is the following, I send a user Id, if the players array contains this Id, return the other id (the array will always have length 2) in the array.
The context is that you can lookup against whom you have played before.
This is what I had, but "players" should be an array and it's not games that I want to return, so
exports.getFriends = function(id, cb){
gameSchema.find({ id: { "$in": "players"} }, function(err, games){
if(err){
return cb(err, null);
}
else{
return cb(null, games);
}
});
};
Can you try this?
exports.getFriends = function(id, cb){
gameSchema.find({ players: id }, function(err, games) {
if (err) {
return cb(err);
}
const players = games.map(game => game.players);
const mergedPlayers = [].concat.apply([], players);
const mappedPlayers = mergedPlayers.map(String); // convert ObjectIds to strings for comparisons.
const idString = String(id);
const filteredPlayers = mappedPlayers.filter(player => player !== idString);
const uniquePlayers = filteredPlayers.filter((player, index, arr) => arr.indexOf(player) === index);
return cb(null, uniquePlayers);
});
};
I'm operating under the assumption that you want an array of the unique player ids that are not the player id you passed in. I kept the vars split apart instead of chaining all of the array methods, in an attempt to improve readability.