【问题标题】:Check if the nested object contains a specific key, then replace a key of the parent object检查嵌套对象是否包含特定键,然后替换父对象的键
【发布时间】:2019-09-26 02:32:03
【问题描述】:

我有一个嵌套对象。

现在,我需要检查对象是否在任何地方都包含“items”作为键,该键始终是“array”,然后将 'type' : 'list' 替换为 '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*?)?\\)"
  }]
 };
 if (Array.isArray(arr.items)) {
  arr.type = "array";
  console.log(arr);
 }
}
<button onclick="convertData()">Click me!</button>

【问题讨论】:

  • 预期输出?

标签: javascript nested-object


【解决方案1】:

您可以使用递归来做到这一点。

  • 创建一个以对象为参数的函数changeValue。
  • 使用Object.hasOwnProperty()检查对象是否有键items
  • 如果包含将 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>

【讨论】:

  • hasOwnProperty() 在这里不是矫枉过正吗?与if(obj.items) 相比,它会产生额外的开销并减慢at least 30% 的操作速度。考虑到您没有检查该解决方案中的任何继承,有什么意义?
猜你喜欢
  • 2020-08-11
  • 1970-01-01
  • 2010-12-13
  • 1970-01-01
  • 2020-04-27
  • 1970-01-01
  • 2021-12-11
  • 2022-11-09
  • 2012-10-17
相关资源
最近更新 更多