I'm struggling to find a good solution to process my array of objects.
I have two arrays:
let structure = ["horizontal","vertical","small","small","small"]
let items = [{"id":1,"title":"xxxxx","format":"horizontal","position":0},
{"id":3,"title":"xxxxx","format":"vertical","position":1},
{"id":6,"title":"xxxxx","format":"small","position":2},
{"id":9,"title":"xxxxx","format":"small","position":3},
{"id":11,"title":"xxxxx","format":"small","position":4}]
Edit: Items are more complex than this: it has about 15 attributes...
structure has a dynamic length and is my reference array. When I change structure I must remap the items array changing the format according to structure. So if I change structure to
let structure = ["horizontal","vertical","vertical","vertical","small"]
The array must change to
let items = [{"id":1,"title":"xxxxx","format":"horizontal","position":0},
{"id":3,"title":"xxxxx","format":"vertical","position":1},
{"id":6,"title":"xxxxx","format":"vertical","position":2},
{"id":9,"title":"xxxxx","format":"vertical","position":3},
{"id":11,"title":"xxxxx","format":"small","position":4}]
This can be done with a map.
This is my Vue method, I map the structure and use the function changeStructure I change the format.
methods: {
changeStructure(object,structure) {
object.format = structure
return object
},
updateCoverElements() {
let structure = this.coverTypes[this.currentCoverVersion]
let elements = this.coverElements
let changeStructure = this.changeStructure
let revisedElement = structure.map(function(structure, index) {
return changeStructure(elements[index],structure)
});
console.log(revisedElement);
}
},
But the problem is that, as I told before, structure has a dynamic length.
So when I change to
let structure = ["horizontal","vertical","vertical"]
Item results must be
let items = [{"id":1,"title":"xxxxx","format":"horizontal","position":0},
{"id":3,"title":"xxxxx","format":"vertical","position":1},
{"id":6,"title":"xxxxx","format":"vertical","position":2}]
This is not a problem, if the new structure length has less elements.
But when I change to
let structure = ["horizontal","vertical","vertical","vertical","vertical","vertical","vertical"]
Item results must be
let items = [{"id":1,"title":"xxxxx","format":"horizontal","position":0},
{"id":3,"title":"xxxxx","format":"vertical","position":1},
{"id":6,"title":"xxxxx","format":"vertical","position":2},
{"id":"","title":"","format":"vertical","position":3},
{"id":"","title":"","format":"vertical","position":4},
{"id":"","title":"","format":"vertical","position":5},
{"id":"","title":"","format":"vertical","position":6}]
And here is the problem: I cannot find a good way to dynamically create an object with the same identical structure as other items objects (a copy), with every field empty except for position, the index of the array, and format.
idandtitleattributes in your bottom-most example?