简体   繁体   English

减少和平整对象的 object

[英]Reduce and flat an object of objects

I am trying to flatten an object of objects which looks something like this,我正在尝试展平看起来像这样的对象的 object,

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

I expect it to be like 075376: ["a","b","c","x","y","z"], 075378: ["a","b","c","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;
              }, {});

This works with lodash, but I couldn't figure out how this is possible with ES6.这适用于 lodash,但我无法弄清楚这在 ES6 中是如何实现的。

You can reduce over the object's entries and add each key to the new object by flattening all the arrays.您可以通过展平所有 arrays 来减少对象的条目并将每个键添加到新的 object。

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

You can use Array.prototype.concat.apply([], array) instead of array.flat() if you can only use ES6.如果只能使用 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);

You could get the entries and flat the values and build a new object.您可以获取条目并平整值并构建新的 object。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM