How to get a subset of a javascript object's properties

后端 未结 27 1655
刺人心
刺人心 2020-11-21 22:46

Say I have an object:

elmo = { 
  color: \'red\',
  annoying: true,
  height: \'unknown\',
  meta: { one: \'1\', two: \'2\'}
};

I want to m

27条回答
  •  感情败类
    2020-11-21 23:34

    Note: though the original question asked was for javascript, it can be done jQuery by below solution

    you can extend jquery if you want here is the sample code for one slice:

    jQuery.extend({
      sliceMe: function(obj, str) {
          var returnJsonObj = null;
        $.each( obj, function(name, value){
            alert("name: "+name+", value: "+value);
            if(name==str){
                returnJsonObj = JSON.stringify("{"+name+":"+value+"}");
            }
    
        });
          return returnJsonObj;
      }
    });
    
    var elmo = { 
      color: 'red',
      annoying: true,
      height: 'unknown',
      meta: { one: '1', two: '2'}
    };
    
    
    var temp = $.sliceMe(elmo,"color");
    alert(JSON.stringify(temp));
    

    here is the fiddle for same: http://jsfiddle.net/w633z/

提交回复
热议问题