I have an array of objects as show below, I'm going to filter out the objects and add into another object of objects (the reason is that I will be storing it into firestore and it only accepts non-arrays) so I'm just going to keep things indexed with numbers but how do I automatically add an object into the list of objects if the object name is not there? (Default object with a value in string)
let data = [ {name: Cat, choice: one, Date: 11/11/22, Time: 503, food: chicken}, {name: Dog, Date: 11/11/22, Time: 802, food: veggies}, {name: Cat, choice: two, Date: 11/11/22, Time: 105, food: beef} ]
for(let i = 0; i<data.length-1; i++) {
let savingData = []
if(data[i].choice == "undefined" || "null") {
data[i].choice = "zero";
}
savingData.push({
name: data[i].name
choice: data[i].choice //missing choices will default to zero as string
food: data[i].food
});
}
for(let j = 0; j<savingData.length-1; j++) {
let objectSavingData = Object.assign({}, savingData[j]);
}
Does not work - did I miss something? or maybe the error is not in this portion of code.. (data structure changed due to its lengthyness, data has arrays of 150+ and object names of over 40, I just simplified it to this but all the data entry are in string)
You should use map function to archive it.
Also use Destructuring & default value.
Here is a snipecode.
const data = [
{ name: "Cat", choice: "one", Date: "11/11/22", Time: 503, food: "chicken" },
{ name: "Dog", Date: "11/11/22", Time: 802, food: "veggies" },
{ name: "Cat", choice: "two", Date: "11/11/22", Time: 105, food: "beef" }
]
const savingData = data.map((record) => {
const { name, choice = 0, Date: date, Time: time, food } = record;
return { name, choice, date, time, food };
});
console.log(savingData);