Reputation: 356
I have nested array and each object contains unique path
property. So i want to update value
property based on condition. Below is reference JSON object
So requirement is to update object in below JSON where path=httpgateway.concurrency.cacheConfig.localConcurrent.0.servers.1
Say current value is localhost:9011
but i want it localhost:9012
[{
"name": "httpgateway",
"type": "Object",
"value": [
{
"name": "concurrency",
"type": "Object",
"value": [
{
"path": "httpgateway.concurrency",
"name": "stalePeriod",
"type": "PORT",
"value": "3000"
},
{
"name": "cacheConfig",
"type": "Object",
"value": [
{
"name": "localConcurrent",
"type": "Object",
"value": [
{
"name": "",
"type": "Array",
"value": [
{
"path": "httpgateway.concurrency.cacheConfig.localConcurrent.0",
"name": "service",
"type": "TEXT",
"value": "/mock/test"
},
{
"name": "servers",
"type": "Object",
"value": [
{
"name": "",
"type": "Array",
"value": [
{
"path": "httpgateway.concurrency.cacheConfig.localConcurrent.0.servers.0",
"name": "hostName",
"type": "URL",
"value": "localhost:9010"
},
{
"path": "httpgateway.cacheConfig.localConcurrent.0.servers.0",
"name": "concurrency",
"type": "NUMBER",
"value": "5"
}
]
},
{
"name": "",
"type": "Array",
"value": [
{
"path": "httpgateway.concurrency.cacheConfig.localConcurrent.0.servers.1",
"name": "hostName",
"type": "URL",
"value": "localhost:9011"
},
{
"path": "httpgateway.cacheConfig.localConcurrent.0.servers.1",
"name": "concurrency",
"type": "NUMBER",
"value": "5"
}
]
}
]
}
]
}
]
}
]
}
]
}
]
}]
Upvotes: 0
Views: 402
Reputation: 36189
You can do it in pure JS like so:
const updateKey = (obj, path, value) => {
if (obj.path === path) {
obj.value = value;
return obj;
}
if (!Array.isArray(obj.value)) {
return obj;
}
obj.value = obj.value.map(item => updateKey(item, path, value));
return obj;
};
const updated = updateKey(data, 'httpgateway.concurrency.cacheConfig.localConcurrent.0.servers.1', 'localhost:9012');
Upvotes: 1