递归转换""在使用下划线的对象中为false

Recursively convert "" to false in object using underscore

本文关键字:quot 对象 false 转换 递归 下划线      更新时间:2023-09-26

我试图将所有""值转换为false使用下划线,它不工作。有更简单的方法吗?

var _ = require("underscore");
var test = {
    "one": "",
    "two": "",
    "three": {
        "four": ""
    },
    "five": "this string is intact"
};

第一次尝试,弄乱了对象

function z(object){ 
    return _.map(object, function(value, key, list){
        if(_.isObject(value)){
            return z(value);
        }else{
            var ret = {};
            ret[key] = (value == "") ? false : value;
            return ret;
        }
    });
}

第二次尝试失败

var _false = function(object){
    var nb = {};
    var _false = function _false(object, parent){
        _.each(object, function(value, key, list){
            if(_.isObject(value)){
                nb[key] = {};
                return _false(value, key);
            }else{
                nb[parent] = (value == "") ? false : value;
            }
        });
    }(object);
    return nb;
}

如果你想修改你的对象,你必须去做!

function z(object){ 
    _.each(object, function(value, key){
        if(_.isObject(value)){
            z(value);
        }else{
            object[key] = (value === "") ? false : value;
        }
    });
}

直接修改你的对象,而不是创建一个新的对象。

_.map()的问题是,它总是返回数组。如果你想以一个对象结束,就像原来的那样,你不能使用它。

为什么需要使用下划线?对于/in,使用纯JS可能更容易。

http://jsfiddle.net/dSZbe/

// Accepts an object to convert '' -> false
var falsify = function(obj) {
    // for each key in the object
    for (var key in obj) {
        // store the value for this key in a local variable
        var value = obj[key];
        // if the value is an empty string
        if (value === '') {
            // update the object, change the value of this key to false
            obj[key] = false;
        // Value is not empty string.
        // So is it an object?
        } else if (typeof value === 'object') {
            // It IS an object! that means we need to do all this again!
            // This is what makes this recursive
            falsify(value);
        }
    }
    // return the modified object, though the object passed
    return obj;
};

// test data
var test = {
    "one": "",
    "two": "",
    "three": {
        "four": ""
    },
    "five": "this string is intact"
};
// proof it works, all empty strings are now `false`.
alert(JSON.stringify(falsify(test)));

但最后,确保你需要这样做…""在JavaScript中是一个假值。这意味着:

var emptyString = "";
if (emptyString) {
  // never gonna happen
} else {
  // always gonna happen
}

所以如果你只是想写像if (test.one) { ... }这样的代码,那么你根本不需要这样做