Find and Get ID with two arrays Javascript

Jaxie :

So I have to csv, one of them contains "Tshirt, ID" and the other one contains only the Tshirt.

After using papaparse I got two arrays like this:

[]
data: Array(6)
0: {tshirt: "a", ID: 121}
1: {tshirt: "b", ID: 132}
2: {tshirt: "c", ID: 147}
3: {tshirt: "d", ID: 97}
4: {tshirt: "e", ID: 76}

[]
data: Array(2)
0: {tshirt: "d", ID: null}
1: {tshirt: "a", ID: null}

What I want to do is generate a new csv with the second array + the ID from the first array. Something like this :

[]
data: Array(2)
0: {tshirt: "d", ID: 97}
1: {tshirt: "a", ID: 121}

I've tried everything and I cant make it work. here is my code:

    var data1=  []
    Papa.parse('a.csv', {
      header: true,
      delimiter: ';',
      download: true,
      dynamicTyping: true,
      skipEmptyLines: true,
      complete: function(results) {
        data1.data = results.data
      }
    });

    var data2 = []
    Papa.parse('b.csv', {
      header: true,
      delimiter: ';',
      download: true,
      dynamicTyping: true,
      skipEmptyLines: true,
      complete: function(results) {
        data2.data = results.data
      }
    });

console.log(data1)
console.log(data2)
amaj :

Here is a solution, that's creating a map from first array:

const data1 = 
[{tshirt: "a", ID: 121},
{tshirt: "b", ID: 132},
{tshirt: "c", ID: 147},
{tshirt: "d", ID: 97},
{tshirt: "e", ID: 76}]

const data2 = 
[{tshirt: "d", ID: null},
{tshirt: "a", ID: null}]

const data1map = data1.reduce ((acc, d) => ({...acc, [d.tshirt]: d}), {})

const result = data2.map(d => ({...d, ID: data1map[d.tshirt].ID}))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=30063&siteId=1