0

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

The userFormJsonObject is a Json object and I wish to delete the node from "element_1" to "element_3" which was defined in items array.

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 "\"element_1\"". 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?

5
  • That's a normal array; it has nothing to do with JSON. It sounds like you actually just want to serialize it to a JSON string. Commented Sep 15, 2016 at 2:53
  • Can you show an example of userFormJsonObject and what you'd like it to look like after the process? Commented Sep 15, 2016 at 2:56
  • 3
    There is no such thing as a "JSON Object" Commented Sep 15, 2016 at 3:03
  • 1
    The variable i will have the values 0, 1, and then 2. Did you mean delete userFormJsonObject[items[i]]? Regarding your updated question, the object shown doesn't have properties called element_1, etc. Regarding preserving the quotes, the object you've shown does not have quotes in its property names. Commented Sep 15, 2016 at 3:05
  • I don't see any object property keys with quotes in that object. Commented Sep 15, 2016 at 3:06

1 Answer 1

1

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]})
console.log(userFormJsonObject);


The for loop version would be

for (var i = 0, l = items.length; i < l; i++) {
    delete userFormJsonObject[items[i]];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, seems I need to refresh my understanding with Json.
@YangXia Again, it's not JSON!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.