Home > Enterprise >  Delete numbered key from js object
Delete numbered key from js object

Time:09-27

I have a js object with id formatted like {'1': ['property1', 'property2'...], '2': ['property1', 'property2'...]...}

I'm using an object rather than a list incase I want to name the properties later.

I used the js code

    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. 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. Any way you can help?

Full context, the use is deleting boxes

CodePudding user response:

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
      }
    ]
  }
}

CodePudding user response:

I realised my mistake! I needed to make it <= to the length of the keys, not just <.

  • Related