我有一个嵌套对象。
现在,我需要检查对象是否始终在“数组”的任何位置包含“ items”作为键,然后将其“ type”:“ list”替换为父对象的“ type”:“ array”。 / p>
它在第一级上很好用,但是当涉及到再次包含“项目”的嵌套对象时,我就卡住了。
function convertData() {
const arr = {
"type": "list",
"items": [{
"type": "list",
"items": [{
"type": "string",
"value": 0,
"unit": "",
"pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$"
}, {
"type": "string",
"value": 0.1875,
"unit": "rem",
"pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$"
}, {
"type": "string",
"value": 0.75,
"unit": "rem",
"pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$"
}, {
"type": "string",
"value": 0,
"unit": "",
"pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$"
}]
}, {
"type": "string",
"value": {
"r": 161,
"g": 161,
"b": 161,
"a": 0.75,
"hex": "#a1a1a1"
},
"pattern": "^rgba?\\(((25[0-5]|2[0-4]\\d|1\\d{1,2}|\\d\\d?)\\s*,\\s*?){2}(25[0-5]|2[0-4]\\d|1\\d{1,2}|\\d\\d?)\\s*,?\\s*([01]\\.?\\d*?)?\\)"
}]
};
if (Array.isArray(arr.items)) {
arr.type = "array";
console.log(arr);
}
}
<button onclick="convertData()">Click me!</button>
答案 0 :(得分:1)
您可以使用递归来实现。
changeValue
。items
检查对象是否具有键Object.hasOwnProperty()
type
更改为"array"
,并在每个项目上递归调用该函数。
function convertData() {
const arr = { "type": "list", "items": [{ "type": "list", "items": [{ "type": "string", "value": 0, "unit": "", "pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$" }, { "type": "string", "value": 0.1875, "unit": "rem", "pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$" }, { "type": "string", "value": 0.75, "unit": "rem", "pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$" }, { "type": "string", "value": 0, "unit": "", "pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$" }] }, { "type": "string", "value": { "r": 161, "g": 161, "b": 161, "a": 0.75, "hex": "#a1a1a1" }, "pattern": "^rgba?\\(((25[0-5]|2[0-4]\\d|1\\d{1,2}|\\d\\d?)\\s*,\\s*?){2}(25[0-5]|2[0-4]\\d|1\\d{1,2}|\\d\\d?)\\s*,?\\s*([01]\\.?\\d*?)?\\)" }] };
changeValue(arr);
console.log(arr)
}
function changeValue(obj){
if(obj.hasOwnProperty('items')){
obj.type = "array";
obj.items.forEach(x => changeValue(x))
}
}
<button onclick="convertData()">Click me!</button>