深入了解Immutable.js

时间:2017-11-09 22:05:21

标签: javascript immutable.js

我希望能够在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']

1 个答案:

答案 0 :(得分:2)

看起来没有任何内置方法可以做到这一点,所以我决定采用深度优先搜索。我使用.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;
}