Reputation: 8960
Hope this isn't too much of a repeating question, I've checked around seen similar but can't seem to solve my issue.
I have a JS object:
var option1Data = {
option: 'Yes',
numberOfPeople: 3,
gender: {} ,
region: {}
};
I want to check if an item is in gender, if not add and set to 1 else increment into. Note that appending it in is important.
Can someone kindly tell me whats wrong:
var input = 'female'; //for purposes of this example
var processGender = function(input) {
if(option1Data['gender'].hasOwnProperty(input)) {
option1Data['gender'][input]++;
}else {
option1Data['gender'][input] = 1;
}
};
User.find({_id: item['userID']}, {gender: 1, country:1}, function(req, foundUser) {
processGender(foundUser[0]['gender']);
});
Upvotes: 0
Views: 84
Reputation: 507
You can't guarantee property order if using an object, you can see this stackoverflow answer for that : Does JavaScript Guarantee Object Property Order?
So appending is out of the question for the structure you're using. But maybe something like below would work for you :
var maleGenderObject= { gender : "male" , count : 0 };
var femaleGenderObject = {gender : "female" , count : 0 };
var option1Data = { option: 'Yes',
numberOfPeople: 3,
gender: [] ,
region: {} };
Then when adding , you can do something like :
var input = "female";
//Nothing exists at the moment, so add the proper object, I added both since there are only two, but you can modify for more genders, but logic will be a bit more complex
if ( option1Data.gender.length == 0 ){
if (input == "female" ){
option1Data.gender.push(femaleGenderObject);
option1Data.gender.push(maleGenderObject);
}
else {
option1Data.gender.push(maleGenderObject);
option1Data.gender.push(femaleGenderObject);
}
}
//If both gender objects exist, determine which one you want, and increment its count
if (option1Data.gender[0].gender == input){
option1Data.gender[0].gender.count++;
}
else {
option1Data.gender[1].gender.count++;
}
This definitely can be optimized, but it's really two variables so I think simple straightforward is better in this case
Another way is to have your gender objects have an order property, and you can use that.
Upvotes: 1
Reputation: 386540
Your code is working fine:
var option1Data = {
option: 'Yes',
numberOfPeople: 3,
gender: {},
region: {}
},
input = 'female';
if (option1Data['gender'].hasOwnProperty(input)) {
option1Data['gender'][input]++;
} else {
option1Data['gender'][input] = 1;
}
document.write('<pre>' + JSON.stringify(option1Data, 0, 4) + '</pre>');
Upvotes: 0