相同的变量显示不同的值

时间:2018-01-19 12:49:04

标签: javascript

var columnsDataList = {
  "checkbox": null,
  "status": "status3",
  "invoiceId": null,
  "invoiceDate": "invoiceDate6",
  "type": "type4"
};
console.log(columnsDataList);


var receivedOrderKey = [];
var receivedOrderKey = Object.keys(columnsDataList).map(function(key) {
  var checkNull = columnsDataList[key];
  if (checkNull != null) {
    receivedOrderKey.push(key);
    console.log(receivedOrderKey)
  }
});


console.log("it's coming blank here", receivedOrderKey);

receivedOrderKey获取所有非空值。但是在最后的console.log中,它显示了5个元素的未定义。我哪里错了?我只想要值不为空的键。

4 个答案:

答案 0 :(得分:0)

键入

时覆盖columnsDataList
var receivedOrderKey = Object.keys(columnsDataList)...

保持逻辑,你可以这样做:

var receivedOrderKey = [];
Object.keys(columnsDataList).map(function (key) {
    var checkNull = columnsDataList[key];
    if(checkNull != null) { 
        receivedOrderKey.push(key);
    }
});    

或清洁:

var receivedOrderKey = Object.keys(columnsDataList).filter(function(key) {
    return columnsDataList[key] !=null
})

答案 1 :(得分:0)

删除<script src="https://www.gstatic.com/charts/loader.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <div class="box-body"> <table class="columns"> <tr> <td> <div class="col-md-6" id="piechart_div"></div> </td> <td> <div class="col-md-6" id="donutchart_div"></div> </td> </tr> </table> </div>

前面的var receivedOrderKey =

Object.keys

答案 2 :(得分:0)

试试这个:

&#13;
&#13;
var columnsDataList = {"checkbox":null,"status":"status3","invoiceId":null,"invoiceDate":"invoiceDate6","type":"type4"};
    console.log(columnsDataList);


    var receivedOrderKey = [];
    Object.keys(columnsDataList).map(function (key) {
        var checkNull = columnsDataList[key];
        if(checkNull != null){ 
            receivedOrderKey.push(key);
        }
     });


   console.log("it's coming blank here",receivedOrderKey);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

我个人不会.map()使用.filter()

&#13;
&#13;
var columnsDataList = {
  "checkbox": null,
  "status": "status3",
  "invoiceId": null,
  "invoiceDate": "invoiceDate6",
  "type": "type4"
};

var receivedOrderKey =
  Object.keys(columnsDataList).filter(k => columnsDataList[k] != null);

console.log(receivedOrderKey)
&#13;
&#13;
&#13;