javascript - 对象内的Javascript数组
问题描述
我有一个像这样的对象内部的数组,例如:
{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)
在我的代码中有一个添加数组和删除数组的选项。如果我删除第二个数组,例如它会变成这样:
{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 ?使对象从低到高管理 THANKS。
解决方案
如果将对象转换为类数组,则可以对它使用数组方法。
类似数组的对象基本上需要一个正length
整数的属性和键。length
需要设置为比最高索引多一。所以,如果你有钥匙,1, 2, 3
那么你需要length: 4
. 是的,这有点误导,因为只有三个元素,但length
更准确地称为“下一个可用索引”。
无论如何,如果你变换你的对象,那么你可以使用Array#splice
和设置目标Function#call
。大多数数组方法是有意通用的,因此它们可以处理任何类似数组的东西:
const obj = {
1: ["foo"],
2: ["bar"],
3: ["baz"],
length: 4
}
//delete starting from index 2 and remove 1 item
Array.prototype.splice.call(obj, 2, 1)
console.log(obj);
注意删除后的索引是如何移动的,并且length
也自动调整了。
如果你不知道length
当前是什么,你可以很容易地找到它:
const obj = {
1: ["foo"],
2: ["bar"],
3: ["baz"]
}
const keys = Object
.keys(obj) //get all keys
.map(Number) //convert to numbers
.filter(key => Number.isInteger(key) && key >= 0); //leave only positive integers
//find the highest
const highestKey = keys.reduce((a, b) => Math.max(a, b), -1);
//set the length to the next possible index
obj.length = highestKey + 1;
//delete starting from index 2 and remove 1 item
Array.prototype.splice.call(obj, 2, 1)
console.log(obj);
推荐阅读
- django - 无法验证 Firebase 令牌
- android - 如何在那些 BOOT_COMPLETE Intent 不像一加 6 那样工作的设备上启动服务
- javascript - 如何用 Python requests-html 抓取评分?
- c# - 依赖注入 IOption 类库
- python - Joblib 持久性和 Pandas
- sql - SQL查询查找一列中有重复的所有记录而不分组
- amazon-web-services - 将文件从一个 AWS 账户中的 S3 存储桶复制到另一个 AWS 账户
- python - python通过函数更新csv行
- python - 有效地展平熊猫中的大型多索引
- excel - VBA识别最高值