简体   繁体   English

从 js object 中删除编号键

[英]Delete numbered key from js object

I have a js object with id formatted like {'1': ['property1', 'property2'...], '2': ['property1', 'property2'...]...}我有一个 js object,其 id 格式为{'1': ['property1', 'property2'...], '2': ['property1', 'property2'...]...}

I'm using an object rather than a list incase I want to name the properties later.我使用的是 object 而不是列表,以防我想稍后命名属性。

I used the js code我使用了js代码

    for(i = 0; i < Object.keys(currentFile).length; i++) {
        if(i == activeBoxId) {
        delete currentFile[i];
        };
        if(i > activeBoxId) {
            currentFile[i - 1] = currentFile[i];
            delete currentFile[i];
        };

to try and preserve numerical order while delete one of a specific index to avoid errors in not finding the id number.尝试在删除特定索引之一时保留数字顺序,以避免在找不到 ID 号时出错。 It doesn't seem to work however, as when I print currentFile, it goes something like 1, 2, 3, 5, 6 - deleting the property I want, but not seeming to delete the next one.然而,它似乎不起作用,因为当我打印 currentFile 时,它会变成 1、2、3、5、6 - 删除我想要的属性,但似乎没有删除下一个。 Any way you can help?有什么可以帮忙的吗?

Full context, the use is deleting boxes 完整的上下文,用途是删除框

In my opinion, you're building it inside out.在我看来,你正在从里到外构建它。 Instead of putting an array of different data inside of numbered objects, you should put objects within an array.与其将不同数据的数组放入编号对象中,不如将对象放入数组中。 If you want to name the set of properties, simply add the name in with the properties.如果要命名属性集,只需将名称与属性一起添加即可。 This would also give you the flexibility of adding and removing properties without breaking the order of everything.这也可以让您灵活地添加和删除属性,而不会破坏所有内容的顺序。

For example, I see this is what you have:例如,我看到这就是你所拥有的:

{
  "Untitled": {
    "0": [
      1,
      2,
      "Title",
      100,
      100
    ],
    "1": [
      2,
      7,
      "Text box.<br> You can write here.",
      100,
      300
    ]
  }
}

I would instead change it into something like this:我会把它改成这样的:

{
  "Untitled": {
    [
      {
        "name": "[You can set a name for the properties here]"
        "a": 1,
        "b": 2,
        "text": "Title",
        "x": 100,
        "y": 100
      },
      {
        "name": "[You can set a name for the properties here]"
        "a": 2,
        "b": 7,
        "text": "Text box.<br> You can write here.",
        "x": 100,
        "y": 300
      }
    ]
  }
}

I realised my mistake, I needed to make it <= to the length of the keys.我意识到我的错误,我需要使它 <= 到键的长度。 not just <.不只是<。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM