js 递归展开对象中的数组

低代码数据结构深层嵌套对象的选项flat为一维数组

// 数据
const ary = [
  {
    "value": {
      "zh-CN": "选项1",
      "en-US": "选项1",
      "ru-RU": "选项1"
    },
    "code": "option-17cc0241",
    "expand": true,
    "children": [
      {
        "value": {
          "zh-CN": "选项1-1",
          "en-US": "选项1-1",
          "ru-RU": "选项1-1"
        },
        "code": "option-0f11b4f4",
        "expand": true,
        "children": [
          {
            "value": {
              "zh-CN": "选项1-1-1",
              "en-US": "选项1-1-1",
              "ru-RU": "选项1-1-1"
            },
            "code": "option-852032ce",
            "expand": false,
            "children": []
          }
        ]
      },
      {
        "value": {
          "zh-CN": "选项1-2",
          "en-US": "选项1-2",
          "ru-RU": "选项1-2"
        },
        "code": "option-af0f1851",
        "expand": true,
        "children": [
          {
            "value": {
              "zh-CN": "选项1-2-1",
              "en-US": "选项1-2-1",
              "ru-RU": "选项1-2-1"
            },
            "code": "option-f9138e1f",
            "expand": false,
            "children": []
          }
        ]
      }
    ]
  },
  {
    "value": {
      "zh-CN": "选项2",
      "en-US": "选项2",
      "ru-RU": "选项2"
    },
    "code": "option-5e81c00d",
    "expand": true,
    "children": [
      {
        "value": {
          "zh-CN": "选项2-1",
          "en-US": "选项2-1",
          "ru-RU": "选项2-1"
        },
        "code": "option-92438f01",
        "expand": false,
        "children": []
      }
    ]
  }
]

// 方法
function flattenDeep (arr) {
	return arr.reduce((pre, cue) => {
		pre.push(cue)
		if (cue.children && cue.children.length > 0) {
			pre = pre.concat(flattenDeep(cue.children))
		}
		return pre
	}, [])
}

// 运行
console.log(flattenDeep(ary))

你可能感兴趣的:(js,javascript,开发语言,ecmascript)