Reduce and flat an object of objects

Viewed 893

I am trying to flatten an object of objects which looks something like this,

{ 
  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"],

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.

2 Answers

You can reduce over the object's entries and add each key to the new object by flattening all the arrays.

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.

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.

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

Related