javascript - How to flatten nested objects in Typescript? - Stack Overflow

I am trying to flatten the following object 'raw' into object 'flat'raw = [{&q

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.

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

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.

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

Share Improve this question asked Jun 2, 2021 at 19:08 yellowSubyellowSub 2091 gold badge4 silver badges14 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

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 pute = (data) => data.map(flatten);

console.log(pute(raw));

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742267226a4412029.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信