【问题标题】:Checking Nesting of objects检查对象的嵌套
【发布时间】:2022-01-15 04:25:29
【问题描述】:

可以有两组对象

首先可以直截了当,没有孩子

const noChildObj = [{
    "id": 1,
    "label": ["Description"],
    "lines": 1,
    "type": "string",
    "precision": 2,
    "width": 167.8
}, {
    "id": 2,
    "label": ["Information", "Ratio"],
    "lines": 2,
    "type": "number",
    "precision": 2,
    "width": 167.8
}, {
    "id": 3,
    "label": ["Tracking", "Error"],
    "lines": 2,
    "type": "number",
    "precision": 2,
    "width": 167.8
}]

所以,在这种情况下,没有 child ,所以属性 'width' 位于最顶层。 其次是对象嵌套发生的地方

所以数组中的每个对象都会有一个子对象


[{
    "id": "257",
    "label": [""],
    "lines": 1,
    "children": [{
        "id": "Description",
        "label": ["Dates"],
        "lines": 1,
        "type": "date",
        "precision": null,
        "width": 839
    }]
}, {
    "id": "258",
    "label": ["Cumulative Return"],
    "lines": 1,
    "children": [{
        "id": 12,
        "label": ["Russell 1000 Value - Price Return"],
        "lines": 1,
        "type": "number",
        "precision": 2,
        "width": 839
    }]
}]

这里每个对象都有一个子对象,属性宽度存在

这种嵌套不仅限于 1 层 最多可以上4级

所以我的用例要求最里面的孩子的宽度是否未定义

我确实意识到,通过递归,我们可以遍历并找出...... 但是有没有什么功能可以用更少的代码来完成。。可能在 lodash

请帮忙

【问题讨论】:

  • 到目前为止,您尝试了哪些方法来自行解决此问题? -> How much research effort is expected of Stack Overflow users?
  • 不清楚您在寻找什么。它是一个接受基于“子”的树并返回一个布尔值的函数,当且仅当width 出现在叶节点上时它才为真?你想添加所有子节点的宽度(递归)吗?还有什么?

标签: javascript arrays recursion


【解决方案1】:

只知道如何处理递归:

const objArray = [{
    "id": 1,
    "label": ["Description"],
    "lines": 1,
    "type": "string",
    "precision": 2,
    "width": 167.8
}, {
    "id": "257",
    "label": [""],
    "lines": 1,
    "children": [{
        "id": "Description",
        "label": ["Dates"],
        "lines": 1,
        "type": "date",
        "precision": null,
        "width": 839
    }]
}]

const getWidthDeep = (el) => el.children && el.children[0]
  ? getWidthDeep(el.children[0])
  : el.width

const result = objArray.map(getWidthDeep)
console.log(result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2016-08-29
    相关资源
    最近更新 更多