javascript - 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?
解决方案
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);
推荐阅读
- mysql - VB6 - 将数据从 mySQL 表插入访问表
- safari - Safari 应用程序扩展内容脚本未加载到 Safari 错误页面上?
- java - GenericUDAFResolver2 已被弃用,我们现在应该如何实现 UDAF?
- node.js - Expressjs - 将标头发送到客户端后无法设置标头
- r - 根据相邻列的值替换多列中的值
- javascript - 如何在 django 模板中访问外键?(列表显示)
- c# - 可访问性问题
- php - 上传图片和文件到论坛
- django - 如何在 dajngo 中使用带有 s3 的静态 div 的背景 url
- docker - 将 docker 容器连接到 docker 桥时如何设置接口名称?