【问题标题】:Reduce and flat an object of objects缩小和展平对象的对象
【发布时间】:2020-10-23 08:55:28
【问题描述】:

我正在尝试展平一个看起来像这样的对象,

{ 
  O75376: { 
    ABC: [], 
    XYZ: ["a", "b", "c"],
    FGH: ["x", "y", "z"]
  },
  O75378: { 
    ABC: [], 
    XYZ: ["a", "b", "c"],
    FGH: ["x", "y", "z"]
  },
}

我希望它像075376: ["a","b","c","x","y","z"], 075378: ["a","b","c","x","y","z"],

const flat = reduce(data, (accumulator, content, key) => {
                accumulator[key] = flatMap(content, (x, y) => {
                  return map(x, b => {
                    return y + '~' + b
                  })
                })
                return accumulator;
              }, {});

这适用于 lodash,但我无法弄清楚这在 ES6 中是如何实现的。

【问题讨论】:

    标签: javascript arrays ecmascript-6 lodash reduce


    【解决方案1】:

    您可以通过展平所有数组来减少对象的条目并将每个键添加到新对象。

    const obj = { 
      "O75376": { 
        ABC: [], 
        XYZ: ["a", "b", "c"],
        FGH: ["x", "y", "z"]
      },
      "O75378": { 
        ABC: [], 
        XYZ: ["a", "b", "c"],
        FGH: ["x", "y", "z"]
      },
    };
    const res = Object.entries(obj).reduce((acc,[key,val])=>(
      acc[key] = Object.values(val).flat(), acc
    ), {});
    console.log(res);

    如果你只能使用 ES6,你可以使用 Array.prototype.concat.apply([], array) 而不是 array.flat()

    const obj = { 
      "O75376": { 
        ABC: [], 
        XYZ: ["a", "b", "c"],
        FGH: ["x", "y", "z"]
      },
      "O75378": { 
        ABC: [], 
        XYZ: ["a", "b", "c"],
        FGH: ["x", "y", "z"]
      },
    };
    const res = Object.entries(obj).reduce((acc,[key,val])=>(
      acc[key] = Array.prototype.concat.apply([], Object.values(val)), acc
    ), {});
    console.log(res);

    【讨论】:

      【解决方案2】:

      您可以获取条目并将值扁平化并构建一个新对象。

      var data = { O75376: { ABC: [], XYZ: ["a", "b", "c"], FGH: ["x", "y", "z"] }, O75378: { ABC: [], XYZ: ["a", "b", "c"], FGH: ["x", "y", "z"] } },
          result = Object.fromEntries(Object
              .entries(data)
              .map(([k, v]) => [k, Object.values(v).flat()])
          )
      
      console.log(result);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        猜你喜欢
        • 2014-01-05
        • 2018-11-16
        • 2019-05-25
        • 2021-03-05
        • 1970-01-01
        • 2021-03-22
        • 2019-04-14
        • 2019-01-17
        • 2021-12-25
        相关资源
        最近更新 更多