簡體   English   中英

使用嵌套的 for 循環比較兩個對象的值並返回修改后的對象數組

[英]Compare values of two objects using nested for loops and return an array of modified objects

我有兩個對象數組:

const testArr1 = [
      {
        event: "Ryan's birthday",
        time: "4:00",
      },
      {
        event: "Steves's birthday",
        time: "2:00",
      },
      {
        event: "Helen's birthday",
        time: "1:00",
      },
      {
        event: "Paola's birthday",
        time: "3:00",
      },
      {
        event: "Jared's birthday",
        time: "9:00",
      },
    ];

const testArr2 = [
      {
        time: "4:00",
        temp: 41,
      },
      {
        time: "6:00",
        temp: 42,
      },
      {
        time: "8:00",
        temp: 43,
      },
      {
        time: "1:00",
        temp: 44,
      },
      {
        time: "3:00",
        temp: 45,
      },
      {
        time: "9:00",
        temp: 46,
      },
    ];

我想創建一個函數,該函數接受這兩個對象數組並返回一個名為dataToDisplay的新對象數組。 dataToDisplay應包含與事件相關的對象。

我希望函數getDataToDisplay通過比較time鍵處的testArr1testArr2值來查看事件是否具有可用的溫度數據,然后給我一個對象數組,這些對象在time值匹配時具有相關的temp數據,或者no matching data foundtime值不匹配時注意。

我的問題是,使用我現在構建的函數,在每次比較時間值時返回 false 的迭代中都會將一個對象推送到dataToDisplay ,因此存在大量重復數據。

這是函數:

const getDataToDisplay = (testArr1, testArr2) => {
  const dataToDisplay = [];

  for (let i = 0; i < testArr1.length; i++) {
    for (let j = 0; j < testArr2.length; j++) {
      let objToPush = {};

      //if times in both objects are equal, push an object containing event, time, and temp value at that time to dataToDisplay
      //break and move on if times are equal
      if (testArr1[i].time === testArr2[j].time) {
        Object.assign(objToPush, {
          event: testArr1[i].event,
          time: testArr1[i].time,
          temp: testArr2[j].temp,
        });
        dataToDisplay.push(objToPush);
        break;
      } else {
        //if times in both objects are NOT equal, push an object containing event, time, and a temp value of "no matching data found"
        Object.assign(objToPush, {
          event: testArr1[i].event,
          time: testArr1[i].time,
          temp: "no matching data found",
        });
        //this is pushing an object every time the condition returns false
        //I only want one object returned if false
        dataToDisplay.push(objToPush);
      }
    }
  }
  return dataToDisplay;
};

這是調用函數時發生的情況

console.log(getDataToDisplay(testArr1, testArr2));
    //logs
    //     [
    //   {
    //     "event": "Ryan's birthday",
    //     "time": "4:00",
    //     "temperature": 41
    //   },
    //   {
    //     "event": "Steves's birthday",
    //     "time": "2:00",
    //     "temperature": "no matching data found"
    //   },
    //   {
    //     "event": "Steves's birthday",
    //     "time": "2:00",
    //     "temperature": "no matching data found"
    //   },
    //   {
    //     "event": "Steves's birthday",
    //     "time": "2:00",
    //     "temperature": "no matching data found"
    //   }
    //   ...
    // ]

    //but I want it to log something like this
    // [
    //   {
    //     event: "Ryan's birthday",
    //     time: "4:00",
    //     temperature: 41,
    //   },
    //   {
    //     event: "Steves's birthday",
    //     time: "2:00",
    //     temperature: "no matching data found",
    //   },
    //   {
    //     event: "Helen's birthday",
    //     time: "1:00",
    //     temperature: 44,
    //   },
    //   ...
    // ];

我如何只為每個事件返回一個新的修改對象,而不是每個比較的結果? 感覺離我好近啊!

您可以為temparatures數組的所有時間獲取一個對象,並通過使用time作為鍵將events數組與times對象的值進行映射。

 const noData = 'no matching data found', events = [{ event: "Ryan's birthday", time: "4:00" }, { event: "Steves's birthday", time: "2:00" }, { event: "Helen's birthday", time: "1:00" }, { event: "Paola's birthday", time: "3:00" }, { event: "Jared's birthday", time: "9:00" }], temperatures = [{ time: "4:00", temp: 41 }, { time: "6:00", temp: 42 }, { time: "8:00", temp: 43 }, { time: "1:00", temp: 44 }, { time: "3:00", temp: 45 }, { time: "9:00", temp: 46 }], times = Object.fromEntries(temperatures.map(({ time, temp }) => [time, temp])), result = events.map(o => ({ ...o, temperature: times[o.time] || noData })); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

您可以使用Array.prototype.reduce並在每個對象走了過來testArr1和匹配找對象temptestArr2使用Array.prototype.find 如果匹配,則將兩者結合起來填充“未找到匹配的記錄”:

 const testArr1 = [{ event: "Ryan's birthday", time: "4:00" }, { event: "Steves's birthday", time: "2:00" }, { event: "Helen's birthday", time: "1:00" }, { event: "Paola's birthday", time: "3:00" }, { event: "Jared's birthday", time: "9:00" }], testArr2 = [{ time: "4:00", temp: 41 }, { time: "6:00", temp: 42 }, { time: "8:00", temp: 43 }, { time: "1:00", temp: 44 }, { time: "3:00", temp: 45 }, { time: "9:00", temp: 46 }]; const getDataToDisplay = (testArr1, testArr2) => { const defaultText = "no matching records found"; return testArr1.reduce((acc, p) => { const matchingTime = testArr2.find(t => t.time === p.time); const temperature = (matchingTime && matchingTime.temp) || defaultText; acc.push({...p, temperature}); return acc; }, []); } console.log(getDataToDisplay(testArr1, testArr2));

您的方法的問題是您將外部 for 循環中的對象與內部 for 循環中的每個對象進行比較。 您只需要在第二個數組testArr2找到具有相同時間的對象,如果沒有找到,則添加消息“未找到匹配的記錄”。

但是在您的情況下,每次與time屬性不匹配時,內部循環都會在輸出數組中推送一個新對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM