首页 > 解决方案 > Lodash 从深度数组中挑选

问题描述

我有一个复杂的对象

{
  "a": 1,
  "b": {"test": {
    "b1": 'b1'
  }},
  "c": {
    "d": [{foo: 1}, {foo: 2}, {foo: 3, bar: 1}, {bar: 12}]
  },
}

我有钥匙列表:

[
  "a", 
  "b.test.b1",
  "c.d[].foo"
]

我想要做的 - 是选择我有键的所有值。问题是 - 我不知道如何处理数组("c.d[].foo")。我不知道数组有多长以及哪些元素有或没有foo

结果应该是

{
  "a": 1,
  "b": {"test": {
    "b1": 'b1'
  }},
  "c": {
    "d": [{foo: 1}, {foo: 2}, {foo: 3}]
  },
}

UPD 如果有人感兴趣,这是我对这个函数的实现:

const deepPick = (input, paths) => {

    return paths.reduce((result, path) => {
      if(path.indexOf('[]') !== -1) {
        if(path.match(/\[\]/g).length !== 1) {
          throw new Error(`Multiplie [] is not supported!`);
        }
        const [head, tail] = path.split('[]');

        const array = (get(input, head) || []).reduce((result, item) => {
          // if tail is an empty string, we have to return the head value;
          if(tail === '') {
            return get(input, head);
          }
          const value = get(item, tail);

          if(!isNil(value)) {
            result.push(set({} , tail, value));
          } else {
            result.push(undefined);
          }
          return result;
        }, []);

        const existingArray = get(result, head);

        if((existingArray || []).length > 0) {
          existingArray.forEach((_, i) => {
            if(!isNil(get(array[i], tail))) {
              set(existingArray, `${i}.${tail}`, get(array[i], tail));
            }
          });
        } else if(array.length > 0) {
          set(result, head, array);
        }
      } else {
        set(result, path, get(input, path));
      }
      return result;
    }, {});
}

这里有一个沙盒可以玩

标签: javascriptarraysobjectlodash

解决方案


map-factory可能有助于以优雅的方式完成这项任务。有关更多详细信息,请参见此处:https ://www.npmjs.com/package/map-factory

代码看起来像这样

const mapper = require("map-factory")();
mapper
  .map("a")
  .map("b.test.b1")
  .map("c.d[].foo");

const input = {
  a: 1,
  b: {
    test: {
      b1: "b1"
    }
  },
  c: {
    d: [{ foo: 1 }, { foo: 2 }, { foo: 3, bar: 1 }, { bar: 12 }]
  }
};

console.log(JSON.stringify(mapper.execute(input)));


推荐阅读