I've got an object which I'd like to simplify, based on a condition:
// input
const image = {
transform: {
mobile: {},
desktop: {}
},
...
}
// output - say we only want mobile transforms
const image = {
transform: {},
...
}
My current approach uses Object.assign to replace the transform key with either it's mobile or desktop child, removing a layer of complexity, as well as unused data. There are keys other than transform in the original image object that need to persist.
However, image.transform seems to be undefined during this operation, although all keys are defined when console logging them.
TypeError: Cannot read properties of undefined (reading 'desktop')
const image = {
id: "asdasd123213",
transform: {
mobile: {
top: 2,
left: 1,
width: 20,
},
desktop: {
top: 20,
left: 145,
width: 260,
}
}
}
const images = [image, image, image];
const isMobile = true;
const newImages = images.map((image) => {
const device = image.transform;
return Object.assign(image, {
transform: device[isMobile ? "mobile" : "desktop"],
});
});
console.log(newImages)