[英]Find json object by key and replace it with other object from complex/nested json array
我試圖通過屬性/鍵從復雜/嵌套的json數組中找到json對象,並將其替換為有角項目中的其他json對象。
我已經使用lodash通過鍵查找json對象,但是對象的json路徑可以在json數組中的任何位置。
這是我的示例json數組:
{
"type": "form",
"title": "title",
"name": "name",
"display": "form",
"path": "path",
"components": [
{
"mask": false,
"tableView": true,
"alwaysEnabled": false,
"label": "",
"rows": [
[
{
"components": [
{
"key": "key1",
"valueProperty": "value",
"selectedKey": "ValueKey"
}
]
}
],
[
{
"components": [
{
"components": [
{
"key": "key2",
"valueProperty": "value",
"selectedKey": "ValueKey"
}
],
"allowMultipleMasks": false,
"showWordCount": false,
"showCharCount": false,
"alwaysEnabled": false,
"type": "textfield",
"input": true,
"widget": {
"type": ""
}
}
]
}
],
[
{
"components": [
{
"labelPosition": "left-left",
"allowMultipleMasks": false,
"showWordCount": false,
"showCharCount": false,
"alwaysEnabled": false,
"input": true,
"widget": {
"type": ""
}
}
]
}
]
],
"header": [],
"numCols": 2
}
]
}
我正在嘗試查找整個json對象(如果它包含“ selectedkey”屬性)並替換為其他對象。
預期結果:
Json object { "key": "key1", "valueProperty": "value", "selectedKey": "ValueKey" } should be replaced with { "key": "key1", "valueProperty": "value", "selectedKey": "ValueKey" }
注意 :Json對象可以出現n次,並且對象的json路徑可以在json數組中的任何位置。
更新:如果您只想檢查該屬性是否存在,則可以對對象進行字符串化並進行includes
檢查,如下所示:
function containsKey(obj, key) {
return JSON.stringify(obj).includes(key);
}
//OR
function containsKey(obj, key) {
return JSON.stringify(obj).indexOf(key) !== -1;
}
您可以使用它來用條件塊替換整個對象:
if (containsKey(obj, 'selectedKey')) {
obj = otherObj;
}
附加解決方案:我還改了我以前的解決方案,該方案替換了selectedKey
,僅檢查了密鑰。 該解決方案的優點是,該函數將在找到selectedKey
之后立即返回,這與JSON.stringify
相對,后者將遍歷每個屬性和值。
function containsKey(obj, targetKey) {
// if the obj is an array, iterate it and call containsKey
if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; i++) {
return containsKey(obj[i], targetKey);
}
} else {
// if it's not an array, it will be an obj
let keys = Object.keys(obj);
let key, value;
// iterate the keys of the object
for (let i = 0; i < keys.length; i++) {
key = keys[i];
value = obj[key];
// if we find the target key, return true
// otherwise, call containsKey on any objects
if (key === targetKey) {
return true;
} else if (typeof value === 'object') {
return containsKey(value, targetKey);
}
}
}
/* by this time we've checked every property of the object,
so we know it does not contain the property or it would
have returned true */
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.