开发者

find object index by string

开发者 https://www.devze.com 2023-03-15 09:50 出处:网络
I have many html-inputs and a very big object with lots of information. Many of those inputs are directly linked to a specific string in the object.

I have many html-inputs and a very big object with lots of information.

Many of those inputs are directly linked to a specific string in the object. E.g.:

<input name="alpha_beta_gamma" type="input" val="newstring" />

and

  obj = {
         alpha: {
             beta: {
                 gamma: 'oldString'
             }
         },
         stuff2: {
             whatever: {
                 weathertoday: 'rainy',
                 sun: false
             },
             phone: '1234567'
         }
  }

the checkbox field for the value "sun" would have the name "stuff2_whatever_sun" but the "phone" field the name "stuff2_phone" and the "gamma" input field the name "alpha_beta_gamma".

Hope you guys get me :)

...and I will use a jQuery focusout event:

 $('input.specialClass').live('focusout', function(){
开发者_如何转开发      obj[whatevercomeshere] = $(this).val();
 });


$('input.specialClass').live('focusout', function(){
  var name = $(this).attr('name');
  var o = obj, parts = name.split("_");
  $.each(parts, function(k, v) {
    if(k == parts.length - 1) {
       o[v] = $(this).val();
    } else {
       o = o[v];
    }
  });  
});


You might want to use eval:

$('input').each( 
   function() {
        var $this = $(this);
        $this.val(eval("obj." + $this.attr('name').replace(/_/g, '.'));
   }
);


Here's one method:

    var obj = {},
        name2json = function(o, name, val){
            var prop = name.splice(0, 1);
            o[prop] = o[prop] || {};
            if(name.length === 0){
                o[prop] = val;
            }else{
                name2json(o[prop], name, val);
            }
        };
    $('input.specialClass').live('focusout', function(){
        name2json(obj, this.name.split('_'), this.value);
     });
0

精彩评论

暂无评论...
验证码 换一张
取 消