I have two datasets. One is an array of strings, and the other one is an array of objects.
I am trying to...
Find the index of an item in an array
And then replace the item with another item in the array of that index
But I can't get it to work on here - https://jsfiddle.net/jt100/pbL2vyn4/7/. (HELP!)
let weeklyDates = [
"2020-12-21",
"2020-12-22",
"2020-12-23",
"2020-12-24",
"2020-12-25",
"2020-12-26",
"2020-12-27"
]
let sitesID = ["1_STANNARY", "3_FOXCAFE"]
let hourlyWastes = [
{
"hourlyWaste": [
{
"coverWaste": [
10
],
"Date": "2020-12-12",
"dayOfYear": "347",
"preparationWaste": [
10
],
"spoilageWaste": [
10
]
}
],
"siteName": "1_STANNARY"
},
{
"hourlyWaste": [
{
"coverWaste": [
20
],
"Date": "2020-12-23",
"dayOfYear": "358",
"preparationWaste": [
20
],
"spoilageWaste": [
20
]
}
],
"siteName": "3_FOXCAFE"
},
]
let hourlyWastesWeeklyDates = []
let num;
for (num = 0; num < weeklyDates.length; num++) {
hourlyWastes.map((data) => {
data.hourlyWaste.filter((item) =>{
if (item.Date == weeklyDates[num]) {
let hourlyWastes = {
siteId: data.siteName,
date: item.Date,
data: {
"coverWaste": item.coverWaste,
"preparationWaste": item.preparationWaste,
"spoilageWaste": item.spoilageWaste
}
}
hourlyWastesWeeklyDates.push(hourlyWastes)
}
})
})
};
let sitesWeeklyDate = []
sitesID.map((data) => {
let siteIdDate = {
weeklyDates: weeklyDates,
siteID: data
}
sitesWeeklyDate.push(siteIdDate)
})
hourlyWastesWeeklyDates.map((data) => {
sitesWeeklyDate.filter((item, iNum) => {
if (item.siteID === data.siteId && item.weeklyDates.includes(data.date)) {
let indexNum = item.weeklyDates.indexOf(data.date)
sitesWeeklyDate[iNum].weeklyDates[indexNum] = data.data
}
})
})
console.log("sitesWeeklyDate",sitesWeeklyDate)
Could you please advise why it is not working?
I am getting the code return below in my console.log which is wrong because the date value "2020-12-12", from siteID "1_STANNARY", do not exists in the weeklyDates array therefore it should not assign an object to replace the date value "2020-12-23"
sitesWeeklyDate = [
{
siteID: "1_STANNARY",
weeklyDates: ["2020-12-21", "2020-12-22", {…}, "2020-12-24", "2020-12-25", "2020-12-26", "2020-12-27"]
},
{
siteID: "3_FOXCAFE",
weeklyDates: ["2020-12-21", "2020-12-22", {…}, "2020-12-24", "2020-12-25", "2020-12-26", "2020-12-27"]
}
the correct return from console.log should be
sitesWeeklyDate = [
{
siteID: "1_STANNARY",
weeklyDates: ["2020-12-21", "2020-12-22", "2020-12-23", "2020-12-24", "2020-12-25", "2020-12-26", "2020-12-27"]
},
{
siteID: "3_FOXCAFE",
weeklyDates: ["2020-12-21", "2020-12-22", {…}, "2020-12-24", "2020-12-25", "2020-12-26", "2020-12-27"]
}
Thank you!