Yang Xia Yang Xia - 11 months ago 40
Javascript Question

Keep double quote from JavaScript array while iterating through the loop

I have a code snippet like the following:

var items = ["element_1", "element_2", "element_3"];

for (int i = 0; i < item.length; i++) {
delete userFormJsonObject[i];

is a Json object and I wish to delete the node from "element_1" to "element_3" which was defined in

Here is what my JSON object looks like in Chrome debugger:

enter image description here

My problem is: the loop will automatically remove the double quote and I wish to preserve the double quote for my loop. I have tried to add
escape character into my array, such as
. But when I passed this into the loop, it seems not working.

I wish my loop runs just like:

delete $scope.userProfileDataFormTrimmed["account_id"];
delete $scope.userProfileDataFormTrimmed["active_directory_flag"];

Is there a good way to solve this problem?

Answer Source

This has nothing to do with quotes as there are no quoted property keys.

Your problem is, instead of using the iteration index i, you would need use items[i] to get the actual value at the iteration index.

You can also use the more modern Array.prototype.forEach method to iterate your items array.

let userFormJsonObject = {
  "element_1": "this is element 1",
  "element_2": "this is element 2",
  "element_3": "this is element 3",
  "element_4": "this is element 4",
  "element_5": "this is element 5",

let items = ["element_1", "element_2", "element_3"];

items.forEach(key => delete userFormJsonObject[key]);
// or items.forEach(function(key){delete userFormJsonObject[key]})

The for loop version would be

for (var i = 0, l = items.length; i < l; i++) {
    delete userFormJsonObject[items[i]];