简体   繁体   English

如何以有效的方法搜索和更新 JsonArray 中的 JsonObject?

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

JsonArray-Example: JsonArray-示例:

[{
    "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.我必须用 Key(name,type) 搜索 JsonObject,如果 jsonObject 与键一起存在想要更新或删除数组中的 jsonObject。

**Normal Solution:**iterate each JsonObject individually,look for the key and perform the operation. **正常解决方案:**单独迭代每个JsonObject,寻找key并执行操作。
PS I want to code all this logic in java not javascript. PS我想用java而不是javascript编写所有这些逻辑。

You can use " LINQ for JavaScript " library.您可以使用“ LINQ for JavaScript ”库。 Very useful library.非常有用的图书馆。 For Example.例如。 we can update like..我们可以像..

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

Your solution is good (n complexity).您的解决方案很好(n 复杂度)。 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.我看到的优化的唯一方法是对列表进行排序(我的意思是,如果从数据库加载它,则按名称和类型对其进行排序,而不是在 Java 中对其进行排序),以便您知道在访问之前知道何时停止搜索列表的末尾。 I'm not sure if binary search algorithm makes sense for two key values.我不确定二分搜索算法对两个键值是否有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM