首页 > 解决方案 > How to clean empty array objects and renumber them?

问题描述

I have a JavaScript object like

{0: [], 1: [0: 'a', 1: 'b'], 2: [], 3: [0: '20']}

I want to get rid of the empty slots in this object and renumber the remaining one, so it has a normal order (0, 1, 2).

I use this function:

function clean(obj) {
    for (var propName in obj) {
        if (obj[propName] === null || obj[propName].length == 0 || obj[propName] === undefined) {
            delete obj[propName];
        }
    }
}

Which clears the object, but then I get

{1: [0: 'a', 1: 'b'], 3: [0: '20']}

But how do I make 1 to 0 and 3 to 1?

标签: javascriptarraysjavascript-objects

解决方案


I recommend using an Array instead of an Object, but you could do something like this:

var obj = {0: [], 1: ['a', 'b'], 2: [], 3: ['20']};

var newObj = Object.keys(obj).reduce(function (acc, k) {
  var objVal = obj[k];
  if (objVal.length) {
    acc[Object.keys(acc).length] = objVal;
  }
  return acc;
}, {});

console.log(newObj);


推荐阅读