Lawrence
Lawrence

Reputation: 727

JSON retrieving object via variable name

I've created a .post form that returns a JSON string and I need to get the data based on the name of the select boxes. please refer to the following example.

JavaScript

$(document).ready(function(){
    $.post('/seller/product_upload/helpers/jpost_product_form_autofill.php',{product_id:$("input[name='product_id']").val()},function(data){
        alert(data);
        if(data!='false'){
            var obj = jQuery.parseJSON(data);
            $("#attributes_table select").each(function(){
                var select=$(this);
                select.find("option").each(function(){
                    var option=$(this);
                    var select_name=select.attr('name');
                    alert(select_name);
                    alert(obj.select_name);
                    if(option.val()==obj.select_name){
                        option.attr('selected','selected');
                    }
                });
            });
        }
    });
});     

The main section of concern here is actually the bottom if part. obj.select_name is not the main object name here. It is actually the name of the selectbox which I had made it coincidental to my array key values parsed in JSON.

But now the system keeps alerting undefined for obj.select_name. Is there any way in which i can parse select_name as a string first before having it parsed as a JSON object?

Upvotes: 2

Views: 5972

Answers (2)

loganfsmyth
loganfsmyth

Reputation: 161447

As mentioned, you need to use square brackets to use an unknown string as an index. That said, you can use jQuery's val function to simplify your code. You don't need to manually set the option values, val can set them just like it can read them. Lke this:

var obj = jQuery.parseJSON(data);
$("#attributes_table select").each(function(){
    var select = $(this);
    select.val(obj[select.attr('name')]);
});

You can also do this, since val will automatically do forEach inside itself.

var obj = jQuery.parseJSON(data);
$("#attributes_table select").val(function(){
    return obj[$(this).attr('name')];
});

Upvotes: 0

Magus
Magus

Reputation: 15104

I believe you want to do that :

var name = 'select_name';
alert(obj[name]);

Upvotes: 3

Related Questions