+ 1

Converting objects into arrays

I have an object for example Const learn = { book: 3, Pen :2, Pencil :1 } How do I convert it to look like this [book, book, book, pen, pen, pencil ] It should vary on the value of each item in d object

31st Jul 2020, 2:58 PM
tony
6 Answers
+ 10
const learn = { Book: 3, Pen :2, Pencil :1 } const foo = Object.keys(learn).reduce((acc, curr) => { return [ ...acc, ...[...new Array(learn[curr])].map(_ => curr) ] }, []);
31st Jul 2020, 8:31 PM
Burey
Burey - avatar
+ 7
I'll break it down: new Array(learn[curr]) => create new array of specified length, in our case the value of learn[curr]. putting the array in [...new Array(learn[curr])] will spread the arrays. Without this step we would get an array of arrays => for learn[curr] = 3: [[null, null, null]] With the spread operator: [null, null, null] The next step is to map the array to the value of curr and again, the outer spread operator (...) is used again to flatten the result and merge with the accumulator (acc)
1st Aug 2020, 6:59 AM
Burey
Burey - avatar
+ 1
const learn ={ book: 3, Pen :2, Pencil :1 } arr=[]; for(let [i,j] of Object.entries(learn)){ for(let k=0;k<j;k++){ arr.push(i); } } console.log(arr);
31st Jul 2020, 3:23 PM
Abhay
Abhay - avatar
+ 1
for(let I in learn) { var key=I; let no=learn[key]; for(let x=0;x<no;++x) { console.log(key); } } Try this u can also store the output for proper output
31st Jul 2020, 3:58 PM
Aayush $aini
Aayush $aini - avatar
0
Burey pls can you explain '[... new Array(learn[curr])] don't understand how it works
1st Aug 2020, 6:45 AM
tony
0
Burey thanks
1st Aug 2020, 7:03 AM
tony