【问题标题】:Automatically renumber object key after item is removed删除项目后自动重新编号对象键
【发布时间】:2016-01-14 20:20:36
【问题描述】:

我有一个看起来像这样的对象:

0

    Object { id="24105",  x="10",  y="4",  more...}
1

    Object { id="24104",  x="6",  y="5",  more...}
2

    Object { id="24103",  x="10",  y="6",  more...}
3

    Object { id="24102",  x="10",  y="3",  more...}
4

    Object { id="24101",  x="8",  y="6",  more...}
5

    Object { id="24100",  x="6",  y="1",  more...}
6

    Object { id="24099",  x="10",  y="8",  more...}
7

    Object { id="24098",  x="8",  y="3",  more...}
8

    Object { id="24097",  x="8",  y="7",  more...}
9

    Object { id="24096",  x="10",  y="2",  more...}
10

    Object { id="24095",  x="8",  y="1",  more...}
11

    Object { id="24094",  x="6",  y="2",  more...}
12

    Object { id="24093",  x="6",  y="8"}
13

    Object { id="24092",  x="8",  y="8",  more...}
14

    Object { id="24091",  x="6",  y="4",  more...}
15

    Object { id="24090",  x="6",  y="7",  more...}
16

    Object { id="24089",  x="10",  y="1",  more...}
17

    Object { id="24088",  x="4",  y="8",  more...}
18

    Object { id="24087",  x="8",  y="2",  more...}
19

    Object { id="24086",  x="6",  y="6",  more...}
20

    Object { id="24085",  x="10",  y="7",  more...}
21

    Object { id="24084",  x="6",  y="3",  more...}
22

    Object { id="24083",  x="8",  y="5",  more...}
23

    Object { id="24082",  x="10",  y="5",  more...}
24

    Object { id="24081",  x="4",  y="7",  more...}

如您所见,对象中的第 12 项包含的数据少于其他项,应将其删除。我已经使用 delete() 来执行此操作,但这不会重新编号其他项目,这会在我在 for 循环中循环对象时导致以后的错误。

我尝试过使用 splice(),但这会导致错误,因为(据我所知)我的对象是对象而不是数组。我不完全确定其中的区别。

有什么想法吗?

谢谢

【问题讨论】:

  • 这是一个对象数组吗?
  • 这看起来不像一个对象...?
  • 使用对象数组,而不是使用数字(实际上是字符串)作为键的对象。
  • 示例“代码”令人困惑。能否请您出示有效的 JS,以便我们更好地理解问题?
  • 您是否必须使用键 12 删除属性,然后将值从下一个键设置为 12 等等?如果是这样,请查看使用数组而不是对象的能力。但是如果你真的需要使用对象,你仍然可以创建处理这种行为的辅助函数。

标签: javascript jquery arrays object javascript-objects


【解决方案1】:

我相信你得到了这样的东西,一个伪装成数组的对象:

{
    0: { id:"24097",  x:"8",  y:"7",},
    1: { id:"24096",  x:"10",  y:"2",},
    2: { id:"24095",  x:"8",  y:"1",}
}

转化为实数数组:

items = Object.keys( items ).map( function( index ){
    return items[index];
});

并使用拼接。

【讨论】:

    【解决方案2】:

    您可以检测到编号。使用Object.keys 删除对象中的属性,并删除少于预期的属性。

    Object.keys() 返回一个元素为字符串的数组 对应于直接在对象上找到的可枚举属性。 属性的顺序与循环给出的顺序相同 手动覆盖对象的属性。

      Object.keys(obj).length
    

    参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

    例如:http://jsfiddle.net/DinoMyte/X6jzs/45/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-18
      • 2012-01-08
      • 2014-04-26
      • 1970-01-01
      • 2022-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多