I wonder how can I create a new jsonObject from overwriting some key values on existing object. In my case I have one jsonObject existingData
, and an order
of type Map<String, Any>.
// order is of type Map<String, Any?>
val keys = listOf("service", "customerContact", "deliveryAddress", "deliveryZipCode", "deliveryZipArea", "deliveryCountryCode", "deliveryPhoneNumber")
val newObject = existingData
.toMap()
.foldLeft(jsonObject()) { acc, entry ->
if (relevantKeys.contains(entry.key)
&& !matching(entry.value, order.get(entry.key))
) acc.set(entry.key, order?.get(entry.key).toString())
else acc.set(entry.key, entry.value.asString)
}
So, here I need to check if the keys
list contains a key on a jsonObject and if the value for that key on the object is different from the value of the order
Map entry. If they are not matching the key on the object should be updated with the value from the order Map. How can I do this, in js I would use reduce, but I am not that familiar with kotlin, and since we can't use fold on JsonObject, I wonder how can I do something like this?
CodePudding user response:
If I understand correctly, you just want this:
val newObject = existingData.deepCopy().apply {
for (key in relevantKeys) {
add(key, Gson().toJsonTree(order[key]))
}
}
add
will overwrite the old value if the key already exists. toJsonTree
converts the Any?
to a JsonElement
. This is assuming that the things inside inside order
can be converted to JSON without any more type information.