javascriptarraysreact-nativevictory-chartsvictory-native

How can I combine 2 arrays key and value in JavaScript?


I'm building my first project, an expense tracking app with React Native. It's going very well.

I would like to concat the following 2 arrays.

[{"Day": "08/31/2022"}, {"Day": "09/01/2022"}, {"Day": "08/31/2022"}, {"Day": "08/31/2022"}, {"Day": "08/31/2022"}, {"Day": "08/31/2022"}]

[{"Amount": "40"}, {"Amount": "300"}, {"Amount": "1715"}, {"Amount": "250"}, {"Amount": "100"}, {"Amount": "200"}]

Final results should be:

[{"Day": "08/31/2022", "Amount": "40"}, {"Day": "09/01/2022","Amount": "300"}, {"Day": "08/31/2022","Amount": "1715"}, {"Day": "08/31/2022","Amount": "250"}, {"Day": "08/31/2022","Amount": "100"}, {"Day": "08/31/2022","Amount": "200"}]

My current code:

  const q = query(collection(db, "users"), where("moneda", "==", "$"));
  const unsubscribe = onSnapshot(q, (querySnapshot) => {
    const dolarCurrency = [];
    const months =[];
    querySnapshot.forEach((doc) => {
        dolarCurrency.push(doc.data().cantidad);
        months.push(doc.data().fecha)
    });

    const hash = months.map((Day) => ({ Day }));
    const hashDolar = dolarCurrency.map(( Amount ) => ({ Amount }))
  });

Everything is working fine, and I'm pulling live data from my firebase to convert it into a chart on React Native with Victory Native for all my personal expenses. So, this would be my last step.

Any help or advice is appreciated!


Solution

  • You can use Array#map and object destructuring as follows:

    const days = [{"Day": "08/31/2022"}, {"Day": "09/01/2022"}, {"Day": "08/31/2022"}, {"Day": "08/31/2022"}, {"Day": "08/31/2022"}, {"Day": "08/31/2022"}],
    
          amounts = [{"Amount": "40"}, {"Amount": "300"}, {"Amount": "1715"}, {"Amount": "250"}, {"Amount": "100"}, {"Amount": "200"}],
          
          output = days.map(({Day},i) => ({Day, ...amounts[i]}));
          
          console.log( output );