筛选 基于某种属性的嵌套数组

我有一个数组。

var data = [{
  "name": "Main Hobbies",
  "checked": false,
  "children": [{
    "name": "Dance",
    "checked": false,
    "children": [{
      "name": "Salsa",
      "checked": true
    }, {
      "name": "Solo",
      "checked": false
    }]
  }, {
    "name": "Sports",
    "checked": false,
    "children": [{
      "name": "Cricket",
      "checked": true
    }]
  }]
}, {
  "name": "Game",
  "checked": false,
  "children": [{
    "name": "PUBG",
    "checked": false
  }, {
    "name": "Cricket",
    "checked": false
  }, {
    "name": "Football",
    "checked": true
  }]
}]

function removeFalseElem(arr) {
  arr.forEach(element => {
    if (Array.isArray(element.children) && element.children.length > 0) {
      element.children = element.children.filter(e => {
        return e.checked === true
      });
      element.children.map(e => {
        delete e['id'], delete e['checked']
      })
    } else {
      removeFalseElem(element.children);
    }
    delete element['id'], delete element['checked'];
  });

}
removeFalseElem(data);
console.log(data);

如何映射 namekeychildrenarray 凡是 checkedtrue. Main hobies 应包含 Salsa 既然是检查。我只是想把这个方法反过来。疑问

输出应该是这样

{
  "Main Hobbies": { Dance: ["Salsa"], Sports: ["Cricket"] },
  Game: ["Football"]
}

只得 checked:true 价值观

解决方案:

你可以检查一个children是否不包含子节点,然后返回一个名称数组,或者用检查过的节点创建一个对象。

const
    getObject = array => array.every(({ children }) => !children)
        ? array.reduce((r, { name, checked }) => checked ? [...(r || []), name] : r, undefined)
        : array.reduce((r, { name, checked, children = [] }) => {
            children = getObject(children);
            if (checked || children) r[name] = children;
            return r;
        }, {}),            
    data = [{ name: "Main Hobbies", checked: false, children: [{ name: "Dance", checked: false, children: [{ name: "Salsa", checked: true }, { name: "Solo", checked: false }] }, { name: "Sports", checked: false, children: [{ name: "Cricket", checked: true }] }] }, { name: "Game", checked: false, children: [{ name: "PUBG", checked: false }, { name: "Cricket", checked: false }, { name: "Football", checked: true }] }],
    result = getObject(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

给TA打赏
共{{data.count}}人
人已打赏
未分类

如何在ggplot2中绘制Posix的小时数据?

2022-9-9 2:01:19

未分类

我可以合理地期望每秒向MySQL服务器写入多少次?

2022-9-9 2:01:21

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索