Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

reactjs - Combine two json arrays into one json array where the data will be completely merged into one single Json in react js

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...