1

Here is my code. The problem is stated at the code lines

<script>


    // sample data created
    var names = ['egard', 'roger'];

    // object k is populated with a key and dynamic values
    // depending on the list of names

    // declare a new object
    var k = {};

    // create k properties according to names data
    for (var i = 0; i < names.length; i++) {

        if (k.hasOwnProperty(names[i])) {
            k[names[i]] = false;
        } else {
            // value is dynamic, can be a number, char
            // that will be used for other purposes
            Object.defineProperty(k, names[i], {
                value : true,
                writable : true
            });
        }
    };



    // using jquery
    $.each(k, function (i, me) {
        // its not going here
        console.log('jquery', me);
    });

    // using native iteration
    for (var i in k) {
        // its not going here
        console.log('native', k[i]);
    }

    // what i want is to go inside the block
    // of $.each or for ()
    // so that i could iterate the object
    // keys and its assign value

    console.log(k);
    // will output
    Object {egard: true, roger: true}


 console.log(k.egard);
    // will output
    // true
</script>

2 Answers 2

5

The problem is your use of Object.defineProperty. By default it will create non-enumerable properties which, as the name suggests, cannot be enumerated by your loops. Just add the enumerable property to the definition:

Object.defineProperty(k, names[i], {
  value : true,
  writable : true,
  enumerable : true
});

Here's a working version.

0
0

you should be cautious about these two key values because they are falseby default:

configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. Defaults to false.

enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to false.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.