Ashish Agarwal
Ashish Agarwal

Reputation: 6283

how to search and update JsonObject in JsonArray in an efficient approach?

JsonArray-Example:

[{
    "name": "table",
    "type": "table",
    "reportId": 7,
    "componentId": 12,
    "width": 0,
    "height": 0,
    "dataType": "DEFAULT"
  },
  {
    "name": "chart",
    "type": "chart",
    "reportId": 7,
    "componentId": 13,
    "width": 0,
    "height": 0,
    "dataType": "DEFAULT"
  }
]

I have to search JsonObject with Key(name,type),if jsonObject exist with the key want to either update or delete the jsonObject from array.

**Normal Solution:**iterate each JsonObject individually,look for the key and perform the operation.
P.S. I want to code all this logic in java not javascript.

Upvotes: 0

Views: 2343

Answers (2)

Rajkumar
Rajkumar

Reputation: 1

You can use "LINQ for JavaScript" library. Very useful library. For Example. we can update like..

Enumerable.From(JsonArray).Where("$.componentId == 12").First().name= "tableName";

Upvotes: 3

Piotr Gwiazda
Piotr Gwiazda

Reputation: 12212

Your solution is good (n complexity). The only way to optimization I see is to have the list sorted (I mean get it ordered by name and type if you load it from database, not sort it in Java) so that you know that you know when to stop searching before getting to the end of the list. I'm not sure if binary search algorithm makes sense for two key values.

Upvotes: 0

Related Questions