I want to change an array to object like this :
array = ["blue" , "txt2" , "red" ,"txt4" , "txt5" , "txt6" ,"txt7" , "txt8" , "txt9" ]
pages = {"page1" :["blue","txt2", "red"] , "page2" : ["txt4", "txt5", "txt6"], "page3" : ["txt7" ,"txt8", "txt9"]
Every key in pages object should have an array value with 3 elements of array (the last key can have less) , so for example if an array have 110 elements we will have 37 pages (page1 , page 2 , ... , page37) and page37 will have 1 elements.
So I want put every 3 elements in array as value of a key in the pages object
But I don't know how to do it.. Thank you for your help
You can do it by iterating over array and extract 3 items from array on every iteration by using splice method, like this:
let array = ["blue" , "txt2" , "red" ,"txt4" , "txt5" , "txt6" ,"txt7" , "txt8" , "txt9", "text10" ]
let pages= {}, i= 1;
while(array.length > 0){
pages[`page${i++}`] = array.splice(0,3)
}
console.log(pages)
with this manner, you loose the original values in the array, if you want to keep items in the array untuched, you can make copy of your original data like let copiedArray = [...array] and then call splice method on the copiedArray and also check the length of copiedArray in the while.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With