简体   繁体   中英

Loop through array of objects, to extract data within nested arrays

Example data set

const data = [
        {
        location: "1A",
        uId: 1,
        notNeededData: null,
        components: [
          {
            modelId: "7654",
            partNumber: "P1",
            description: "It's a desk.",
            notNeededData: null,
            location: "office1"
          },
          {
            modelId: "1234",
            part: "P2",
            description: "It's a chair",
            notNeededData: null,
            location: "office1"
          }
        ]
      },
      {
        location: "2B",
        uKeyId: 1,
        notNeededData: null,
        components: [
          {
            modelId: "9876",
            partNumber: "P8",
            description: "The best headrest",
            notNeededData: null,
            location: "office2"
          },
          {
            modelId: "7463",
            partNumber: "P5",
            description: "The stool",
            notNeededData: null,
            location: "office2"
          }
        ]
      }
    ];

Desired result set as a new array of objects, as follows:

         [
          {
            id:1,
            uId: 1,
            location: "1A",
            modelId: "7654",
            partNumber: "P1",
            description: "It's a desk."
          },
          {
            id:2,
            uId:1,
            location: "1A",
            modelId: "1234",
            part: "P2",
            description: "It's a chair"
          },
          {
            id:3,
            uId: 2,
            location: "2B",
            modelId: "9876",
            partNumber: "P8",
            description: "The best headrest"
          },
          {
            id:4,
            uId: 2,
            location: "2B",
            modelId: "7463",
            partNumber: "P5",
            description: "The stool"
          }
        ]

I have tried iterating through the array with the following function, but I only succeed in duplicating only a few value sets.

const getNewDataSet = (d) => {
      let newArr = [];
    
      for (let i = 0; i < d.length; i++) {
        let obj = {};
        obj["id"] = i + 1;
        obj["uId"] = d[i].uId;
        obj["location"] = d[i].location;
        for (let k = 0; k < d[i].components.length; k++) {
          obj["modelId"] = d[i].components[k].modelId;
          obj["partNumber"] = d[i].components[k].partNumber;
          obj["description"] = d[i].components[k].description;
          newArr.push(obj);
        }
      }
      return newArr;
    };

Please let me know if there is any additional information required, or anything that I may have left out.

Greatly appreciated, thank you.

That's my Solution, In my opinion, don't use a lot of indices to not be confused, so I use forEach() when I looped on the component to pick each component easy and you also need to empty the object again after you push it to clear all old data from it and also I declared a variable (id) to give each component a Unique Id and increment it each cycle of the loop as [i] it's not unique in this case as there is more than one component in the same Object of input data.

        const getNewDataSet = (data) => {
          let newArr = [];
          let obj = {};
          let id = 1;
          for (let i = 0; i < data.length; i++) {
              const currObj = data[i];
              currObj.components.forEach((comp) => {
                   obj["id"] = id;
                   obj["uId"] = currObj.uId || currObj.uKeyId;
                   obj["location"] = data[i].location;
                   obj["modelId"] = comp.modelId;
                   obj["partNumber"] = comp.partNumber;
                   obj["description"] = comp.description;
            newArr.push(obj);
            obj = {};
            id++;
        })
   }
   return newArr;
 };

Maybe there is a better solution but, it's working. I hope this helps you

 const data = [{ location: "1A", uId: 1, notNeededData: null, components: [{ modelId: "7654", partNumber: "P1", description: "It's a desk.", notNeededData: null, location: "office1" }, { modelId: "1234", part: "P2", description: "It's a chair", notNeededData: null, location: "office1" } ] }, { location: "2B", uKeyId: 1, notNeededData: null, components: [{ modelId: "9876", partNumber: "P8", description: "The best headrest", notNeededData: null, location: "office2" }, { modelId: "7463", partNumber: "P5", description: "The stool", notNeededData: null, location: "office2" } ] } ]; const formatRespnse = (data) => { let records = [], mainComponents = [] i = 1; data.forEach((record) => { let components = {}; let newData = {}; record.components.forEach((component) => { newData = { id: i, uId: record.uId, location: record.location, modelId: component.modelId, partNumber: component.partNumber || component.part, description: component.description, } records.push(newData); i++; }); }); return records; } console.log(formatRespnse(data));

You could use map function to simplify array loop, like this :

const extractData = data => {
  let id = 1;

  return data.map(d => {
    return d.components.map(dd => {
      const newObj = {
        id: id,
        uId: d.uId || d.uKeyId,
        location: d.location,
        modelId: dd.modelId,
        partNumber: dd.partNumber || dd.part,
        description: dd.description
      }
      id += 1;
      return newObj;
    });
  });
}

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