检查对象是否具有空属性

时间:2018-08-03 19:40:55

标签: javascript node.js

假设我有以下JS对象

sql

我将收到这样的对象,它具有更多的属性,可以是data = { name: "John", dataOfBirth: "", externalId: 2548, email: "john@email.com", mobile: "" } StringInteger。为了更新数据库,我无法用空信息覆盖有效信息。

我可以全部尝试undefined,但这似乎不可行。

有什么方法可以扫描所有属性,而不必命名每个属性并删除所有空的/未定义的属性?

2 个答案:

答案 0 :(得分:1)

您可以简单地遍历对象键并检查每个元素的值是否为空。

var data = {
        name: "John",
        dataOfBirth: "",
        externalId: 2548,
        email: "john@email.com",
        mobile: ""
    }

    for(var key in data) {
        if(data[key] === "") {
           console.log(key + " is blank. Deleting it");
           delete data[key]
        }
    }

答案 1 :(得分:1)

您不能这样做吗?还是我错过了什么?

Highcharts.wrap(Highcharts.Chart.prototype, 'drawSeriesLabels', function(proceed) {
    proceed.apply(this, Array.prototype.slice.call(arguments, 1));

    var chart = this,
        plotTop = chart.plotTop,
        plotLeft = chart.plotLeft,
        series = chart.series,
        height = chart.yAxis[0].height,
        x1,
        x2,
        y1,
        y2;

    x1 = ((series[0].graphPath[1] + plotLeft) * 2 + series[0].graphPath[4] + plotLeft) / 3;

    y1 = (height + plotTop + series[0].graphPath[2] + plotTop + series[0].graphPath[5] + plotTop) / 3;

    x2 = (series[1].graphPath[1] + plotLeft + (series[1].graphPath[4] + plotLeft) * 2) / 3;

    y2 = ((series[1].graphPath[2] + plotTop) * 2 + series[1].graphPath[5] + plotTop) / 3;

    series[0].labelBySeries.attr({
        x: x1,
        y: y1,
        align: 'center'
    });

    series[1].labelBySeries.attr({
        x: x2,
        y: y2,
        align: 'center'
    });
});

给你这个:

Object.entries(data).filter(([k,v],i)=>!!v)

"[ [ "name", "John" ], [ "externalId", 2548 ], [ "email", "john@email.com" ] ]" 会将值转换为布尔值,在此阶段,您将滤除null,NaN和undefined。确实,如果要对嵌套对象进行尝试,则必须递归执行此操作,因为!!始终为真。更好的办法是递归和异步地复制对象,过滤掉虚假的原语,最后传递一个回调以进行字符串化。

编辑:

下面的人提到了一些您可能想要保留的虚假值,例如0。在这种情况下,将它们链接起来:

!!Object()