Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Looping through an object only returns the first object

I am trying to reshape some data to be used in a table. To do this I am mapping over an array and then looping over an object inside of it to create a new object with the data I want in it. The issue Im having is if the object contains more than one object inside of it I only get a new object for the first item.

I am trying to get a new object for each of the objects held inside changedProperties

Can anyone help? / Explain?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is a working example:

const MOCK_DATA = [
  {
    triggeredByID: "d5ae18b7eb6f",
    triggeredByName: "name",
    changedProperties: {
      LastName: {
        __oldValue: "Mallory",
        __newValue: "Mallorie",
      },
      Suffix: {
        __oldValue: "DO",
        __newvValue: "NP",
      },
    },
    createdAt: "2022-06-01T10:20:21.329337652Z",
  },
  {
    triggeredByID: "d5ae18b7eb6f",
    triggeredByName: "John",
    changedProperties: {
      State: {
        __oldValue: ["TX", "AL"],
        __newValue: ["TX", "AL", "FL"],
      },
      City: {
        __oldValue: "Austin",
        __newValue: "San Antonio",
      },
    },
    createdAt: "2022-06-01T10:20:21.329337652Z",
  },
];

const changedProperties = MOCK_DATA.map((item, idx) => {
    for (const [key, value] of Object.entries(item.changedProperties)) {
      return {
        field: key,
        old: item.changedProperties[key].__oldValue,
        new: item.changedProperties[key].__newValue,
        name: item.triggeredByName,
        createdAt: item.createdAt,
      };
    }
  });
  
  console.log(changedProperties)

>Solution :

Yes, if you return inside a for-loop, its scoped to the function. Meaning you will return from the entire function on the first iteration of your loop. Try this instead:

const changedProperties = MOCK_DATA.map((item, idx) => {
   return Object.entries(item.changedProperties).map(([key, value]) => {
      return {
        field: key,
        old: item.changedProperties[key].__oldValue,
        new: item.changedProperties[key].__newValue,
        name: item.triggeredByName,
        createdAt: item.createdAt,
      };
    }
  });
  
  console.log(changedProperties)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading