0

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.

1
  • can you add a jsfiddle? Commented Sep 15, 2015 at 7:56

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you . It's working fine. Your explanation was so helpful.
0

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]

1 Comment

JavaScript specification mentions nothing about order of keys - they are not sorted in any way

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.