1

给一个数据结构如下
var data = [
{

"name": "手机",
"childs": [
    {
        "name": "iPhone",
        "childs": [
            {"name": "iPhone X"},
            {"name": "iPhone XR"},
            {"name": "iPhone XS"},
        ]
    },
    {
        "name": "HUAWEI",
        "childs": [
            {"name": "HUAWEI Mate 20"},
            {"name": "HUAWEI Mate 20 X"},
            {"name": "HUAWEI Mate 20 Pro"},
        ]
    }
]

}
];

然后让封装一个函数, 根据名称得到其遍历的路径. 例如参数是 HUAWEI Mate 20. 那么函数返回 手机 / HUAWEI/HUAWEI Mate 20. 要求函数可以适用多层的数据结构, 例如上面的数据只有三层深度, 如果扩展为 10 层的话函数仍然可以适用.

这个题目的其实就是一个树的遍历, 然后返回这个遍历路径. 但是想了半天没想到如何写

2019-05-21 提问
4 个回答
0

已采纳
function f() {
    var s = getPath("HUAWEI Mate 20 Pro", data[0], "");
    console.log(s)
}

/**
 * 
 * @param search  查询的子节点
 * @param parent  根节点
 * @param path    路径
 * @returns {*}
 */
function getPath(search, parent, path) {
    path = path + "/" + parent.name;
    if (parent.name == search) return path;
    if (parent.childs != null && parent.childs.length > 0) {
        var childs = parent.childs;
        for (var i = 0; i < childs.length; i++) {
            var t = getPath(search, childs[i], path);
            if (t == undefined || t == null || t == "") {
                continue;
            } else {
                return t;
            }
        }
    }
}
3
let path = [];
function getTree(data,extend) {
  for (let z = 0; z < data.length; z++) {
       const _data = data[z];
       let extendarray = extend?JSON.parse(JSON.stringify(extend)):[];
       if (_data.childs) {
            extendarray.push(_data.name)
            getTree(_data.childs,extendarray)
        }else{
           extendarray.push(_data.name)
            path.push(extendarray)
        }
    }
}
getTree(data);
console.log(path);

这样

2
const find = (target, childArr, curPath = '') => {
  for (let i = 0; i < childArr.length; i += 1) {
    const {name, childs} = childArr[i]
    const path = `${curPath}${curPath ? '/' : ''}${name}`
    if (name === target) return path
    if (childs) {
      const rtn = find(target, childs, path)
      if (rtn) return rtn
    }
  }
}

console.log(find('iPhone XR', data))
1

我刚刚在 MDN 看到了, forEach 没有返回值。看来还是对这个方法理解不够

Ayden · 5月21日

展开评论
1
function getNamePath(data, name) {
  let namePath = ''

  function _getNamePath(childs, parentNamePath) {
    for (const child of childs) {
      if (child.name === name) {
        namePath = parentNamePath + '/' + name
      } else {
        const childs = child.childs
        if (childs && childs.length > 0) {
          let newParentNamePath = parentNamePath + '/' + child.name
          _getNamePath(childs, newParentNamePath)
        }
      }
    }
  }
  _getNamePath(data, '')
  return namePath
}

console.log(getNamePath(data, 'HUAWEI Mate 20 Pro'))

撰写答案

推广链接