简体   繁体   中英

How to fetch the key value from object in angularjs

I have stored the value in an object in the following format,

$scope.modelName = {
    name: {}
};

The value was stored like {"APLLE":true,"ORANGE":true} . I am trying to fetch only the key and I am trying to store it in another object using for loop. I couldn't get the value

for (var i = 0; i < 2 ; i++) {        
    $scope.fruitRulesRules.push({
        field: "fruitName",
        subType: "equals",
        value: Object.Keys($scope.modelName.name[i])
    });
}

Thanks in advance.

Object.keys() returns an array of the keys in the object. You need to select the key for index your looping over. You were close but no cigar.

see fiddle: http://jsfiddle.net/pzky9owf/1/

var modelName = {
        name: {
            APPLE: true,
            ORANGE: true
        }
    },
    fruitRulesRules = [];

for (var i = 0; i < 2; i++) {
    fruitRulesRules.push({
        field: 'fruitName',
        subType: 'equals',
        /*
            This bit was close. You could could also cache the Object.keys in 
            another variable so its not called in every itteration of the loop if it doesnt change often
        */
        name: Object.keys(modelName.name)[i]
    });
}

console.log(fruitRulesRules);

EDIT: Also you've got Object.Keys , capital K , its lower case k but i presume that's a typo writing the fiddle.

EDIT AGAIN: As @KrzysztofSafjanowski mentioned in another comment you can't guarantee the order of Object.keys() so even though above works it may not give the desired results.

Ive updated the fiddle to show a different way where the order of the keys is not important: http://jsfiddle.net/pzky9owf/2/

I believe you are accessing the key wrong, does this give you some insight?

Object.keys({"APLLE":true,"ORANGE":true})[0] //returns "Apple"

So your solution is possibly:

Object.Keys($scope.modelName.name)[i]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM