简体   繁体   中英

Nested for loops, is there a better way?

I need to remove empty attributes from objects stored in an array, without touching the original array.

here is my code:

// first I create a copy of the array
parsedShapes = [];
  for (var i in shapes) {
    parsedShapes.push(shapes[i]);
}
// then for each objects in the new array, I delete all the empty attributes.
for (var i in parsedShapes) {
  var objects = parsedShapes[i];
  for (var j in objects) {
    if (objects[j] === "") {
      delete objects[j];
    }
  }
}

This code works, but I wanted to know if there was a better way to handle this operation.

Thanks.

To create a copy of an array, just do this:

var newArray = oldArray.slice(0);

That aside, I can't really think of any simpler way to filter out empty values, other than just not having them there in the first place.

if you can not change the value of 'shapes', I would try something like this:

var parsedShapes = shapes.map(function(item){
    var obj = {};
    for(var i in item){
        if(item[i] || (item[i]===false || item[i]===0)){ obj[i] = item[i]; }
    }
    return obj
});

This way you only have to do one cycle through 'shapes' instead of having to iterate through 'shapes' to create 'parsedShapes' then iterate through 'parsedShapes' to weedout the blanks.

if(item[i] || (item[i]===false || item[i]===0)){ obj[i] = item[i]; }

This will weed out anything of of the values 'null' or "". I am assuming that something with the value '0' or 'false' is not considered "empty".

Note filter() only works one arrays. So, if the items in the the collection are objects, then using filter() wont work.

You'd probably do this with a filter function, like:

var filtered = object_filter(parsedShaped, function (key, shape) {
    return shape !== "";
});

Where filter is something like:

function object_filter(array) {
    var result = {};
    object_map(object, function (key, value) {
        if (filter_function(key, value)) {
            result[key] = value;
        }
    });
    return result;
}

Most framework will have a function like this. If not, write your own :)

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