简体   繁体   中英

How to flatten nested objects in Typescript?

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.

在此处输入图像描述

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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