我有嵌套的数组,每个对象都包含唯一的path属性。所以我想根据条件更新value属性。下面是引用JSON对象
因此需要在下面JSON where path=httpgateway.concurrency.cacheConfig.localConcurrent.0.servers.1中更新对象
假设当前值为localhost:9011,但我想要它为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"
}
]
}
]
}
]
}
]
}
]
}
]
}
]
}]发布于 2020-06-18 13:27:05
你可以用纯JS来实现,如下所示:
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');https://stackoverflow.com/questions/62442835
复制相似问题