How to flatten nested objects in Typescript?

Viewed 2714

I am trying to flatten the following object 'raw' into object 'flat'

raw = [    {
      "id":"123",
      "Date":"12/12/2020",
      "Type":{
         "id":"456",
         "desc":"test1"
      }    },    {
      "id":"124",
      "Date":"12/12/2020",
      "Type":{
         "id":"456",
         "desc":"test2"
      }    } ]
flat =[   {
      "id":"123",
      "Date":"12/12/2020",
      "desc":"test1"
      },    
      {
      "id":"124",
      "Date":"12/12/2020",
      "desc":"test2"
      }]

I attempted the following:


   let flatData:any = []
    const flattenObject = (obj:any) => {
      const flattened:any = {}
    
      Object.keys(obj).forEach((key) => {
        if (typeof obj[key] === 'object' && obj[key] !== null) {
          Object.assign(flattened, flattenObject(obj[key]))
        } else {
          flattened[key] = obj[key]
        }
      })
      flatData.push(flattened)
      console.log(flattened)
      return flattened
    }

Result I get from the code snippet above.

enter image description here

...........................................................................................

3 Answers

You can use object destructuring in TypeScript.

const raw = [{
  "id": "123",
  "Date": "12/12/2020",
  "Type": {  "id": "456",  "desc": "test1" }
}, {
  "id": "124",
  "Date": "12/12/2020",
  "Type": {  "id": "456", "desc": "test2" }
}];

const mapped = raw.map(({ id, Date, Type: { desc } }) => ({ id, Date, desc }));

console.log(mapped);
.as-console-wrapper { top: 0; max-height: 100% !important; }

The function you are using to flatten the object is correct, however, the nested id property in the Type property has the same property name as the top-level id property. When you flatten the object, that top-level id value is overwritten with the nested id value.

Solutions:

  1. If you have control of the data, you could rename the nested id property to something else.
  2. In the flattenObject function, you could prefix the nested property with the parent property name. i.e.
const flattenObject = (obj:any, prefix = '') => {
      const flattened:any = {}
    
      Object.keys(obj).forEach((key) => {
        if (typeof obj[key] === 'object' && obj[key] !== null) {
          Object.assign(flattened, flattenObject(obj[key], prefix))
        } else {
          flattened[prefix + key] = obj[key]
        }
      })
      flatData.push(flattened)
      return flattened

Here is a solution that works in case you have only one depth level and if you want to flatten objects, no matter what's the property name:

const raw = [
  {
    id: "123",
    Date: "12/12/2020",
    Type: {
      id: "456",
      desc: "test1",
    },
  },
  {
    id: "124",
    Date: "12/12/2020",
    Type: {
      id: "456",
      desc: "test2",
    },
  },
];

const flatten = (obj) =>
  Object.assign(
    {},
    Object.fromEntries(
      Object.values(obj)
        .filter((x) => typeof x === "object")
        .map((x) => Object.entries(x))
        .flat(1)
    ),
    Object.fromEntries(
      Object.entries(obj).filter(([, x]) => typeof x !== "object")
    )
  );

const compute = (data) => data.map(flatten);

console.log(compute(raw));

Related