3

I have an ajax call like so:

 $.ajax({
        type: "GET",
        url: "/api/connection/getCommunities",
        dataType: 'json',
        cache: false,
        success: function (data) {
            console.log(data);
            var communityDropdown = $("#communtiyDropdown");
            $.each(data, function (key, value) {
                communityDropdown.append($("<option />").val(key).text(key));
            });


        }
    });

This takes the data and puts the key into the dropdown menu. My data looks like the image attached (this a screenshot of my console log in chrome)

enter image description here

Now this same dropdown that I populated with using the ajax call, I created an on change event for it outside the ajax call.

$("#communtiyDropdown").on('change', function () {
        console.log($(this).val());
    });

Now what I am looking to do is what ever key the user selects (example A2T) I want to populate another dropdown with the keys values....I hope this makes sense.

What I have tried so far is the following.

Created this array before my ajax call,

var items = [];

Then push the items into this array inside the ajax call inside the each

items.push({key: value});

My problem I am having is the key shows up as key, not the key variable just the word key, the values are populating like they should, but how do I get key variable for an object which is being pushed into the array ?

UPDATE

solved this by changing items.push({key: value}); to items[key] = value;

2 Answers 2

3

If you want to use the value of a variable as the property name of an object, you need to use bracket notation. Try this:

var obj = {};
obj[key] = value;
items.push(obj);
Sign up to request clarification or add additional context in comments.

Comments

2

solved this by changing items.push({key: value}); to items[key] = value;

1 Comment

did you solve it yourself or cuz of Rory answer? if cuz of rory plz accept his answer

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.