简体   繁体   中英

Looping through nested data and displaying object properties and values

In my React app, I'm looking for a clean way to loop through the following dynamic data structure and display the object properties and values.

Sample data:

data: {
   company: [
      {
         company_name: "XYZ Firm",
         company_email: "hello@xyz.com",
         company_phone: 91982712,
      }
   ],
   shareholders: [
     {
         shareholder_name: "Lin",
         percentage: 45
     },
     {
         shareholder_name: "Alex",
         percentage: 10
     },
   ],
   employees: [
     {
         employee_name: "May",
         employee_email: "may@xyz.com"
     },
   ]
}

The output I want is:

company_name: XYZ Firm
company_email: hello@xyz.com
company_phone: 91982712

shareholder_name: Lin
shareholder_percentage: 45

shareholder_name: Alex
shareholder_percentage: 10

employee_name: May
employee_email: may@xyz.com

This is what I've tried so far:

//data contains the entire object
const profileInfo = Object.keys(data).map(key => {
   let profileSection = [];
   for (let values of data[key]) { //retrieve the objects of each "section" e.g., company, shareholders
      Object.keys(values).map(key => {
         profileSection.push(<p>{key}: {values[key]}</p>);
      })
   }
   return profileSection;
})

I'm able to achieve the intended results but I'm not sure if it's the best solution in terms of performance. Having nested Object.keys().map seems a bit off to me.

Note: User will be able to add more shareholders/employees.

Here is a somewhat shorter version using Object.values() and Object.entries() .

 var data = { company: [ { company_name: "XYZ Firm", company_email: "hello@xyz.com", company_phone: 91982712, } ], shareholders: [ { shareholder_name: "Lin", percentage: 45 }, { shareholder_name: "Alex", percentage: 10 }, ], employees: [ { employee_name: "May", employee_email: "may@xyz.com" }, ] }; let profileInfo = []; Object.values(data).flat().forEach((item) => { Object.entries(item).forEach(([key, value]) => { profileInfo.push(key + ": " + value); }); }); console.log(profileInfo);

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