缩小并展平一个对象的对象

Reduce and flat an object of objects

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

{ 
  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 中如何实现。

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

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; }

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

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);