Home > database >  Flatten nested object Typescript
Flatten nested object Typescript

Time:11-10

I have a an interface,I need to write a function to flatten the object .I want the 'Phrase' in single tier object

 interface IRule {
  activationDate: number;
  contentSources: string[];
  createdBy: string | undefined;
  dateCreated: number;
  dateUpdated: number;
  publishFailed: boolean;
  name: string;
  ruleCustomFields: {
    CustomFields: {
      phrases: string[];
      warning: string;
    };
  };
  ruleId: string;
}

data:

 {
  "activationDate": 1664390668.694,
  "contentSources": [""],
  "createdBy": "iusername”,
  "dateCreated": 1664390668.694,
  "dateUpdated": 1664390668.694,
  "name": "charm",
  "publishFailed": false,
  "ruleCustomFields": {
    "CustomFields": {
      "phrases": ["fake-chrm"],
      "warning": "blocked"
    }
  },
  "ruleId": "1233",

}

I tried to pull phrases out but it throws error saying 'item.ruleCustomFields.CustomFields is undefined'(I only need the first phrase in that array)

  const flatItems = rules.map((item) => ({
    ...item,
    phrase: item.ruleCustomFields.CustomFields.phrases[0]
  }));

CodePudding user response:

It looks like you do not have only 1 rule, as you are doing a map operation.

Moving my comment here:

Do all rules have CustomFields? I am guessing some values in the array has a null or undefined value which is what gives you the error.

It would be better to have a null-check as:

phrase: item.ruleCustomFields.CustomFields?.phrases[0] || ''

Where the ? operator will return null if value does not exists, and the || operator will make a nice empty string default to avoid null phrases.

  • Related