首页 > 解决方案 > 对象内的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。

标签: javascriptarraysobject

解决方案


如果将对象转换为类数组,则可以对它使用数组方法。

类似数组的对象基本上需要一个正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);


推荐阅读