最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论