【问题标题】:Deep find in Immutable.js在 Immutable.js 中深入查找
【发布时间】:2017-11-09 22:05:20
【问题描述】:

我希望能够在 Immutable.js 中找到深度嵌套值的 keyPath。怎么填写这个函数deepFind得到我想要的?

const map = Immutable.fromJS({
    a: { 
        a1: 1,
        b1: 2
    },
    b: {
        b1: 3
        b2: 4,
        b3: 5
    }
});

function deepFind(map, value) {
    /* ??? */
}

deepFind(map, 4); // returns ['b', 'b2']

【问题讨论】:

  • 遍历map的keys,检查每个key的value是否===value,如果是则返回[key, map[key]],否则检查map[key]是否为对象,如果是则调用@ 987654326@

标签: javascript immutable.js


【解决方案1】:

看起来没有任何内置方法可以做到这一点,所以我决定使用深度优先搜索。我使用.toKeyedSeq() 搜索了所有具有相同代码的集合类型。

注意:如果您的集合包含自身,此函数将永远挂起。

import Immutable from 'immutable';

function deepFind(root, value, path = Immutable.List()) {
  if (root === value) {
    return path;
  }

  if (!Immutable.isImmutable(root)) {
    // this is a leaf node, and it's not the value we want.
    return undefined;
  }

  for (const [key, child] of root.toKeyedSeq()) { 
    const result = deepFind(child, value, path.push(key));
    if (result) {
      return result;
    }
  }

  // no path is found
  return undefined;
}

【讨论】:

    猜你喜欢
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    相关资源
    最近更新 更多