具有数字键的对象的等效拼接

时间:2019-03-03 15:39:43

标签: javascript

说我有一个像这样的对象:

const obj = {
        0: { name:'zero'},
        1: { name: 'one'}, 
        3: { name: 'three'},
        4: { name: 'four'}
    };

我想对其进行“打包”,这样,如果键是数组索引,则数组中就不会有间隙。

{
    0: { name:'zero', ...},
    1: { name: 'one', ...}, 
    2: { name: 'three', ...},
    3: { name: 'four', ...}
}

我不想替换obj,我想破坏性地替换它。

我的计算方式有两个工作:1)找到缺少键的间隙(最终,我想对任何数目的间隙进行此操作),2)通过移动值来填充间隙向后。

在我寻找缺少的钥匙的循环中,break似乎马上就发生了。另外,其余代码(我认为可能有用)非常冗长。谁能帮助我找到更好的解决方案?

const obj = {
        0: { name:'zero'},
        1: { name: 'one'}, 
        3: { name: 'three'},
        4: { name: 'four'}
    };
    
let expectedKey = 0
for (const [key, value] in obj) {
    if (key !== expectedKey) break
    expectedKey++
}

let missingKey = expectedKey
let keys = Object.keys(obj)
console.log(`missing key is ${missingKey} <<< why is this wrong`)

for (let k = missingKey; k < keys.length; k++) {
    let nextKey = (k == keys.length-1) ? null : k+1
    if (nextKey) obj[k] = obj[nextKey]
}

lastKey = keys[keys.length-1]
delete obj[lastKey]

console.log(obj[3])

2 个答案:

答案 0 :(得分:3)

您可以将值分配给对象。

var obj = { 0: { name:'zero'}, 1: { name: 'one'},  3: { name: 'three'}, 4: { name: 'four'} };

obj = Object.assign({}, Object.values(obj));

console.log(obj);

O,如有必要,您可以将值重新分配给新键。

var obj = { 0: { name:'zero'}, 1: { name: 'one'},  3: { name: 'three'}, 4: { name: 'four'} },
    i = 0,
    k;

for (k in obj) {
    if (+k !== i) {
        obj[i] = obj[k];
        delete obj[k];
    }
    i++;
}

console.log(obj);

为剩余键使用队列。这适用于多个剩余键。

var obj = { 0: { name:'zero'}, 1: { name: 'one'},  3: { name: 'three'}, 4: { name: 'four'} },
    i = 0,
    k,
    queue = [];

for (k in obj) {
    if (+k !== i) {
        obj[i] = obj[k];
        queue.push(+k);
    }
    if (queue[0] === i) queue.shift();
    i++;
}
while(queue.length) delete obj[queue.shift()];

console.log(obj);

答案 1 :(得分:0)

您可以在{}内传播Object.values()以获得连续的密钥:

const obj = {
        0: { name:'zero'},
        1: { name: 'one'}, 
        3: { name: 'three'},
        4: { name: 'four'}
    };
    
const newObj = { ...Object.values(obj) }

console.log(newObj)

Object.values()返回values的数组。当您将其散布在{}内时,索引将变成keys