Object.keys()
function is used to return an array of the keys within the object. It's important to correctly select the key when looping through. While your attempt was close, it didn't quite hit the mark.
Check out this demo on jsfiddle: 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 part was almost there. You could also consider storing Object.keys in a separate variable to avoid recalculating in each iteration if it doesn't change frequently.
*/
name: Object.keys(modelName.name)[i]
});
}
console.log(fruitRulesRules);
UPDATE: And just a quick note, you should be using Object.keys
with a lowercase k
, not uppercase as seen in the fiddle example.
ANOTHER UPDATE: As pointed out by @KrzysztofSafjanowski in another comment, the order of keys returned by Object.keys()
is not guaranteed, so while the above approach may work, it might not always yield the expected results.
I've made changes to the fiddle to demonstrate an alternative method that doesn't rely on key order: http://jsfiddle.net/pzky9owf/2/