Search code examples
javascriptobjectjavascript-objectsindexed

how to modify properties of an nested object?


I have the following nested object and I need to leave the "alias" property blank and the "group" property set to true for all "entries" and "exits". I also need to delete the whole "parameters" object. Would there be a way to do it all in one function? I've tried to apply the delete Object method but it doesn't work as it's an indexed object.

{
  "1": {
    "x": 114,
    "y": 135,
    "properties": {
      "id": 1,
      "entries": {
        "entry_0": {
          "id": 1,
          "alias": "do",
          "group": false
        }
      },
      "exits": {
        "exit_0": {
          "id": 1,
          "alias": "re",
          "group": false
        }
      },
      "parameters": {
        "parameter_0": {
          "id": 3,
          "group": false
        }
      },
      "order": 1
    }
  },
  "2": {
    "x": 700,
    "y": 104,
    "properties": {
      "id": 1
      "entries": {
        "entry_0": {
          "id": 1
          "alias": "do"
          "group": false
        }
      },
      "exits": {
        "exyt_0": {
          "id": 1
          "alias": "re"
          "group": false
        }
      },
      "parameters": {
        "parameter_0": {
          "id": 3
          "alias": "mi"
          "group": false
        }
      },
      "order": 2
    }
  }
}

the desired nested object would be the following

{
  "1": {
    "x": 114,
    "y": 135,
    "properties": {
      "id": 1,
      "entries": {
        "entry_0": {
          "id": 1,
          "alias": "",
          "group": true
        }
      },
      "exits": {
        "exit_0": {
          "id": 1,
          "alias": "",
          "group": true
        }
      },
      "order": 1
    }
  },
  "2": {
    "x": 700,
    "y": 104,
    "properties": {
      "id": 1
      "entries": {
        "entry_0": {
          "id": 1
          "alias": ""
          "group": true
        }
      },
      "exits": {
        "exyt_0": {
          "id": 1
          "alias": ""
          "group": true
        }
      },
      "order": 2
    }
  }
}

what I've tried is the following, managing to delete the "parameters" object but I can't access the "label" property of each "entry" and "exit

const nedtedObjectsValues = Object.values(nestedObjects);
for (object of nedtedObjectsValues) {
   delete object.properties.parameters;

}

if anyone can give me an idea of how to approach this function. Thank you in advance.


Solution

  • In JavaScript, to reference numeric object properties, you need to use the square brackets syntax:

    object.1 // bad
    object[1] // good
    

    You can delete numeric property like this:

    delete object[1];