Reputation: 109
For example, say I have data = [{car: "ford", year: "1982"}, {car: "toyota", year: "1999"}]
.
//factory function
function Car(type, year) {
return {
type,
year,
identity() {
return "I am a " + year + " " + type
}
}
}
let arr = []
data.forEach((x) => {
// would this be the correct way to turn these into factory function
// objects?
arr.push(Car(x.car, x.year))
})
Is there a better way of doing this so that each Car() has a variable associated with it?
Upvotes: 1
Views: 221
Reputation: 617
var data = [{car: "ford", year: "1982"}, {car: "toyota", year: "1999"}];
function Car(type, year) {
return {
type,
year,
identity() {
return "I am a " + year + " " + type
}
}
}
// Use Map. Map iterates over your array, at each
// element it will call the supplied callback argument
// with the current element. Whatever your function returns
// will be mapped to a new array
// at the same index as the element passed to your callback
const arr = data.map(({ car, year }) => Car(car, year))
console.log(arr);
Upvotes: 1
Reputation: 63579
It depends if you want your variable names to be meaningful.
You could assign the objects to another object with the car + year as the keys. I've used reduce
here to iterate over the dataset and create the new object. (I've also made a couple of other changes to the code.)
const data = [{car: "ford", year: "1982"}, {car: "toyota", year: "1999"}];
function Car({ car, year }) {
return {
car,
year,
identity() {
return `I am a ${year} ${car}`;
}
};
}
const cars = data.reduce((obj, { car, year }) => {
const id = `${car}${year}`;
obj[id] = Car({ car, year });
return obj;
}, {});
console.log(cars);
console.log(cars.ford1982.identity());
If you just want to have an id
instead, as your comment indicates, you could map
over the data and inject the iteration index into the data instead. map
returns an array of objects. You can then use array methods like find
to pick out cars based on their properties.
const data = [{car: "ford", year: "1982"}, {car: "toyota", year: "1999"}];
function Car({ id, car, year }) {
return {
id,
car,
year,
identity() {
return `I am a ${year} ${car}`;
}
};
}
const cars = data.map(({ car, year }, index) => {
return Car({ id: `Car${index}`, car, year });
});
console.log(cars);
console.log(cars[0].identity());
console.log(cars.find(car => car.id === 'Car1').identity());
Upvotes: 0