简体   繁体   中英

How to remove empty,null, undefined values from array within object using underscore

I want to remove all the keys associated with null, I tried with _.filter, _.compact, _.reject, but nothing works for me, am using latest version of underscore 1.8.3

This is what I tried:

_.reject(Obj,function (value) {
    return value===null;
})

_.compact(Obj)

Object:

    var Obj =  {
  "pCon": [
    {
      "abc": null,
      "def": null,
      "ghi": {
        "content": "abc"
      }
    },
    {
      "abc": null,
      "def": {
        imgURL: "test.png"
      },
      "ghi": null
    },
    {
      "abc": {
        "key": "001"
      },
      "def": null,
      "ghi": null
    }
  ]
}

A solution in plain Javascript in a recursive style.

 function deleteNull(o) { if (typeof o === 'object') { Object.keys(o).forEach(function (k) { if (o[k] === null) { // or undefined or '' ...? delete o[k]; return; } deleteNull(o[k]); }); } } var object = { "pCon": [{ "abc": null, "def": null, "ghi": { "content": "abc" } }, { "abc": null, "def": { imgURL: "test.png" }, "ghi": null }, { "abc": { "key": "001" }, "def": null, "ghi": null }] }; deleteNull(object); document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>'); 

 for (var i in Obj["pCon"]) {
  if (Obj["pCon"][i]["abc"] === null || Obj["pCon"][i]["abc"] === undefined) {
  // test[i] === undefined is probably not very useful here
    delete Obj["pCon"][i]["abc"];
  }
  if (Obj["pCon"][i]["def"] === null || Obj["pCon"][i]["def"] === undefined) {
  // test[i] === undefined is probably not very useful here
    delete Obj["pCon"][i]["def"];
  }
  if (Obj["pCon"][i]["ghi"] === null || Obj["pCon"][i]["ghi"] === undefined) {
  // test[i] === undefined is probably not very useful here
    delete Obj["pCon"][i]["ghi"];
  }
}

it works in jsfiddle https://jsfiddle.net/3wd7dmex/1/

This is the solution using underscore. Please note that this will not recursively go deeper into the structure like Nina's solution does. But you can extend this to mirror that behaviour if need be.

 var obj = { "pCon": [{ "abc": null, "def": null, "ghi": { "content": "abc" } }, { "abc": null, "def": { imgURL: "test.png" }, "ghi": null }, { "abc": { "key": "001" }, "def": null, "ghi": null }] }; var result = _.chain(obj).map(function(value, key) { value = _.map(value, function(singleObj) { return _.pick(singleObj, _.identity) // pick the keys where values are non empty }); return [key, value]; }).object().value(); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>'); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM