Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

First Array contains the below array of elements

"Data": [
    {
      "ID": 1,
      "Name": "XYZ",
      "Driver": "Assigned",
}
{
      "ID": 2,
      "Name": "PQR",
      "Driver": "UnAssigned",
}

Second Array is of different set of data

"Data": [
        {
          "Updated": "KLM",
          "Date": "22/01/2020",
    }
    {
          "Updated": "PQR",
          "Date": "23/01/2020",
    }
{
          "Updated": "OOO",
          "Date": "23/07/2020",
    }

I want the final json as below

    "Data": [
        {
          "ID": 1,
          "Name": "XYZ",
          "Driver": "Assigned",
          "Updated": "KLM",
          "Date": "22/01/2020",
    
    }
    {
          "ID": 2,
          "Name": "PQR",
          "Date": "23/01/2020",
          "Updated": "PQR",
          "Date": "23/01/2020",
    }
 {
          "ID": 2,
          "Name": "PQR",
          "Driver": "UnAssigned",
          "Updated": "PQR",
          "Date": "23/01/2020",
    }
 {
          "ID": "",
          "Name": "",
          "Driver": "",
          "Updated": "OOO",
          "Date": "23/07/2020",
    }

If both the arrays are of different lengths, the field should go as blank like the last one. How can we do in reactjs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.7k views
Welcome To Ask or Share your Answers For Others

1 Answer

You need a zip like functionality available in Python.

I created the below snippet that should be of help.

const firstArray = [
    {
        ID: 1,
        Name: "XYZ",
        Driver: "Assigned",
    },
    {
        ID: 2,
        Name: "PQR",
        Driver: "UnAssigned",
    },
];

const secondArray = [
    {
        Updated: "KLM",
        Date: "22/01/2020",
    },
    {
        Updated: "PQR",
        Date: "23/01/2020",
    },
    {
        Updated: "OOO",
        Date: "23/07/2020",
    },
];

// get an empty object from first array with "" as values
firstSchema = Object.keys(firstArray[0]).reduce((acc, cur) => {
    acc[cur] = "";
    return acc;
}, {});

// get an empty object from second array with "" as values
secondSchema = Object.keys(secondArray[0]).reduce((acc, cur) => {
    acc[cur] = "";
    return acc;
}, {});

// create an empty schema object merged with both above schemas
emptySchema = { ...firstSchema, ...secondSchema };

const zip = (a, b) =>
    Array.from(Array(Math.max(b.length, a.length)), (_, i) => ({
        ...emptySchema,
        ...a[i],
        ...b[i],
}));

console.log(zip(firstArray, secondArray));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...