adding to json property that may or may not exist yet

前端 未结 8 2160
清酒与你
清酒与你 2021-01-04 04:12

let say I want to do this:

  var dashboard = {};
  var page = \"index\";

  $(\'.check\').click(function(){ 
    $(thi         


        
相关标签:
8条回答
  • 2021-01-04 04:41

    I don't think there's a good builtin way to do this, but you could always abstract it with a function.

    function getProperty(obj,prop){
        if( typeof( obj[prop] ) == 'undefined' ){
            obj[prop] = {};
        }
        return obj[prop];
    }
    

    Then you use

    getProperty(dashboard,'pages')['pagename']

    or

    getProperty(getProperty(dashboard,'pages'),'pagename');
    

    As mentioned, $.extend will make this less burdensome.

    0 讨论(0)
  • 2021-01-04 04:41

    Well I guess you need this:

    var dashBoard = new Array();
    if(!dashboard['page123']) {
        dashBoard.push('page123');
    } else {
    ...do what you want
    }
    

    Seems you are dealing with XML.

    0 讨论(0)
  • 2021-01-04 04:44

    If you use underscore >= 1.9.0, you can use property and propertyOf:

    d={a: {b: "c"}}
    _.property(["a", "b", "c", "e"])(d)   // undefined
    _.property(["a", "b"])(d)             // "c"
    _.propertyOf(d)(["a", "b", "c", "e"]) // undefined
    _.propertyOf(d)(["a", "b"])           // "c"
    
    0 讨论(0)
  • 2021-01-04 04:47
    var foo = dashboard['pages'] || {};
    foo['pagename'] = 'your thing here';
    dashboard['pages'] = foo;
    

    Explaining: the first line will check if the first value is null, undefined or... false (don't think this is a problem here): if it is, create a new object, if it is not, will use it.

    0 讨论(0)
  • 2021-01-04 04:49

    I would do it with the ternary operator:

    dashboard['pages'][page] = dashboard['pages'][page] ? dashboard['pages'][page] : {};
    

    That will do the trick no matter if it's set/null or whatever.

    0 讨论(0)
  • 2021-01-04 04:51

    The best solution for my case was to do a Object prototype

     /**
     * OBJECT GET
     * Used to get an object property securely
     * @param object
     * @param property
     * @returns {*}
     */
    Object.get = function(object, property) {
        var properties = property.split('.');
        for (var i = 0; i < properties.length; i++) {
            if (object && object[properties[i]]) {
                object = object[properties[i]];
            }
            else {
                return null;
            }
        }
        return object;
    };
    

    And then you can get your property like this

    var object = { step1: { step2: { step3: ['value1', 'value2'] }}}
    Object.get(object, 'step1.step2.step3'); // ['value1', 'value2']
    Object.get(object, 'step1.step2.step3.0'); // 'value1'
    Object.get(object, 'step1.step2.step3.step4'); // null
    

    Hope it helps :)

    0 讨论(0)
提交回复
热议问题