将单独的数组深层键转换为所需的类型(数组或对象)

Convert separate array deep keys to required type (array or object)

本文关键字:数组 类型 对象 转换 单独      更新时间:2023-09-26

如何仅将"items"(对象类型)键转换为数组类型:

var arr = [{
  "title": "Custom title",
  "id": "id1",
  "icon": "fa fa-reorder",
  "other": {
    "3991": {
      "title": "Some title",
      "link": "#",
      "icon": "",
      "items": {
        "3992": {
          "title": "Some title",
          "link": "#",
          "icon": ""
        }
      }
    },
    "3993": {
      "title": "Some title",
      "link": "#",
      "icon": ""
    }
  }
}];

收件人:

var arr = [{
  "title": "Custom title",
  "id": "id1",
  "icon": "fa fa-reorder",
  "other": {
    "3991": {
      "title": "Some title",
      "link": "#",
      "icon": "",
      "items": [{
          "title": "Some title",
          "link": "#",
          "icon": ""
        }]
    },
    "3993": {
      "title": "Some title",
      "link": "#",
      "icon": ""
    }
  }
}];

我需要每次单独选择对什么类型的更改指定键。我已经搜索了一些阵列步行者,但没有成功。

示例:

var newArr = change_key_type({
 'arr' : arr,
 'key' : 'items',
 'type' : 'array'
});

您可以迭代并为所有items构建一个新数组。

function walk(a) {
    typeof a === 'object' && Object.keys(a).forEach(function (k) {
        if (k === 'items' && typeof a.items === 'object') {
            a.items = Object.keys(a.items).map(function (k) {
                walk(a.items[k]);
                return a.items[k];
            });
            return;
        }
        walk(a[k]);
    });
}
var arr = [{ "title": "Custom title", "id": "id1", "icon": "fa fa-reorder", "other": { "3991": { "title": "Some title", "link": "#", "icon": "", "items": { "3992": { "title": "Some title", "link": "#", "icon": "" } } }, "3993": { "title": "Some title", "link": "#", "icon": "" } } }];
arr.forEach(walk);
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');