对象内部的Javascript数组 [英] Javascript Arrays inside object

查看:46
本文介绍了对象内部的Javascript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我在对象内部有一个数组:

i have a arrays inside object like this for example:

{1: Array(4), 2: Array(4), 3: Array(4)}
1: (4) ["11111", "2020-04-02", "14:07", 1]
2: (4) ["22222", "2020-04-02", "14:07", 2]
3: (4) ["3333333", "2020-04-02", "14:07", 3]
(from console log)

在我的代码中,有一个添加数组和删除数组的选项.例如,如果我删除第二个数组,它将变为:

in my code there is a option to add array and delete array . And if I delete the second array for example its will become to this:

{1: Array(4), 3: Array(4)}
1: (4) ["11111", "2020-04-02", "14:07", 1]
3: (4) ["3333333", "2020-04-02", "14:07", 3]
(from console log)

如何使第三个对象变为2?使对象从低到高进行管理谢谢.

How do I make the third object become to 2 ? Make the object manage from the low to the high THANKS.

推荐答案

在上面的对象中,当您删除第二个数组时,仅删除了该键,这对其他键没有影响.因为对象键充当标识符来访问与该键相对应的值的位置.

In the object above, when you delete the second array, only that key is removed and this has no impact on other keys. Because object keys act as an identifier to access the location of value corresponding to that key.

如果您希望其他键应将编码重置为顺序.请使用数组数组而不是将数组作为值的对象.

If you want that other keys should reset accoding to order. Please use array of arrays instead of objects having arrays as values.

数组-带数字索引的有序项目对象-具有任何有效字符串或数字索引的无序项目.

Array - ordered items with numeral indices Object - unordered items with any valid string or number indices.

如果需要使用对象,这是手动执行此操作的解决方案-

对于需要删除的索引 i ,解析下一个索引(数字大于 i )以采用key = key-1,即,将其索引键减小1.

For the index i that needs to be removed, parse the next indices (numerically greater than i) to take key = key - 1, i.e., decreasing their index key by 1.

// index is treated from 1 to n.
const deleteElement = (delete_index, obj) => {
    const keyCount = Object.keys(obj).length;

    // move all elements with keys > delete_index to previous index
    for(let i=delete_index; i<=keyCount; i++) {
        obj[i] = obj[i+1]
    }
    // delete last element
    delete obj[keyCount]
}


这篇关于对象内部的Javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆