In my current project, I'm attempting to replicate the functionality of CSS using JavaScript. Specifically, I am working with an index of items in a mapped array and assigning each item a unique index number.
computed: {
parsedItems() {
return this.items?.map((obj, index) => {
return {
...obj,
}
})
}
}
To provide some context for why I am pursuing this approach, I am creating a grid layout consisting of blocks containing various data such as images, titles, URIs, and text. I aim to implement the equivalent of :nth-child(7n + 1) in CSS using Vue 2 framework but with JavaScript.
The parsed items in the array contain images which are utilized by a custom component designed to handle image-related tasks, including setting the aspect ratio based on the height-to-width ratio of each image.
After researching how the :nth-child selector works in CSS,
:nth-child(3n + 3)
Essentially translates to:
(3 x 0) + 3 = 3 = 3rd Element
(3 x 1) + 3 = 6 = 6th Element
(3 x 2) + 3 = 9 = 9th Element
etc.
In my attempt to achieve this functionality in JavaScript, I initially tried multiplying the index by 7 and adding values from 1 to 7 accordingly:
computed: {
parsedItems() {
return this.items?.map((obj, index) => {
return {
...obj,
aspectRatio:
7 * index + 1 === 1
? someAspectRatio
: 7 * index + 2 === 9
? someAspectRatio
...etc
}
})
}
}
However, this approach did not produce the desired results as the map method does not reset at every 7th element and the math calculation was off.
Subsequently, I experimented with the modulo operator (%) to improve the implementation:
computed: {
parsedItems() {
return this.items?.map((obj, index) => {
return {
...obj,
aspectRatio:
index % 7 === 0
? someAspectRatio
: index % 3 === 0
? someAspectRatio
: index % 2 === 0
? someAspectRatio
: someAspectRatio
}
})
}
}
While this second attempt was more promising, it still fell short as the modulo results became mixed up with increasing numbers of items in the array.