Aiyoub A.
Aiyoub A.

Reputation: 5391

how to access object keys by index in jquery?

I have a general JavaScript function which fill data to list as follows:

// manage all drop down list control
var ajaxFillDropDownList = function (options, ddl) {

    ddl.find("option").remove();

    ddl.addClass("form-control required")
        .append($("<option />").attr("value", "")
        .text("------ Please Select a item --------")
        );

    $.ajax(options)
        .done(function (data) {

            var result = "";

            if (data.value) {
                result = JSON.parse(data.value);
            }

            $.each(result, function (rowIndex, r) {
                ddl.append($("<option></option>")
                    .val(r.?)
                    .text(r.?);
            });
        })
        .fail(function (error) {
            ddl.append($("<option />").attr("value", "").text("error in load"));
        });
}

The following function is called:

// -- Fill dropdownlist
var fillMyList = function () {
    try {

        var options = {
            type: "POST",
            url: "/User/GetUserList",
            data: JSON.stringify({}),
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        }

        ajaxFillDropDownList(options, $("#ddlUser"));

    } catch (error) {
        ShowClientErrorMessage("client Error", error.stack, error.message);
    }
}

I want get keys of result as dynamically in $.each loop. I'm tired of using the code below, But the list is filled with key name.

.val("r." + Object.keys(r)[0])

I will be grateful if someone could guide me.

Upvotes: 1

Views: 2374

Answers (2)

RJ-
RJ-

Reputation: 136

For Quick reference the Fiddle link https://jsfiddle.net/rj1405/sd4mxpae/2/

Key: Object.keys(obj)[0]

Value : here obj is a object within result or my myObject array.

obj[Object.keys(obj)[0]]

You will be able to run bellow code.

var myObject = [{
  property1: 'value 1'
}, {
  property2: 'value 2'
}]

var selectElement = document.getElementById('selectElement');
$.each(myObject, function (i, r) {
$(selectElement).append($('<option>',{
        value: Object.keys(r)[0],
        text : r[Object.keys(r)[0]]
    }));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectElement">
</select>

Upvotes: 1

Aiyoub A.
Aiyoub A.

Reputation: 5391

I changed .val("r." + Object.keys(r)[0]) to

.val(eval("r." + Object.keys(r)[0]))
.text(eval("r." + Object.keys(r)[1]))

code was successfully implemented.

Upvotes: 0

Related Questions