附加到JS对象

时间:2016-02-14 18:43:19

标签: javascript node.js

希望这不是一个重复的问题,我已经检查过类似但似乎无法解决我的问题。

我有一个JS对象:

var option1Data = {
    option: 'Yes',
    numberOfPeople: 3,
    gender: {} ,
    region: {}
};

我想检查一个项目是否属于性别,如果没有添加并设置为1则增加为。请注意,附加它很重要。

有人可以告诉我什么是错的:

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']);
});

2 个答案:

答案 0 :(得分:1)

如果使用对象,您无法保证属性顺序,您可以看到此stackoverflow的答案: Does JavaScript Guarantee Object Property Order?

因此,对于您正在使用的结构来说,追加是不可能的。 但也许像下面这样的东西对你有用:

var maleGenderObject= { gender : "male" , count : 0 };
var femaleGenderObject = {gender : "female" , count : 0 };
var option1Data = { option: 'Yes',
    numberOfPeople: 3,
  gender: [] ,
  region: {} };

然后在添加时,您可以执行以下操作:

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++;
}

这绝对可以优化,但它确实是两个变量,所以我认为在这种情况下简单直白更好

另一种方法是让您的性别对象具有订单属性,您可以使用它。

答案 1 :(得分:0)

您的代码运行正常:



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>');
&#13;
&#13;
&#13;