Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning and array into an object

I have an array of elements containing iPhone models and 4 values that come after it, like this:

const arr = ['ip6s+', '35', '15',  '10', '10', 'ip7', '40', '20', '15', '15']

I want to turn this into an object that looks like this:

const Obj = {
   'ip6s+': ['35', '15',  '10', '10'],
   'ip7+' : ['90', '60', '35', '30']
}

Where the first object is the phone model and every fourth is its values. How to do that?

like image 788
Wiil Waal Avatar asked Jul 21 '26 19:07

Wiil Waal


1 Answers

You can use slice:

const arr = ['ip6s+', '35', '15',  '10', '10','ip7', '40', '20', '15','15'];

const obj = {};

const n = 4; // the number of values after the model name

for (var i = 0; i < arr.length; i += n + 1) {
  obj[arr[i]] = arr.slice(i + 1, i + n + 1);
}

console.log(obj);
like image 185
MrGeek Avatar answered Jul 23 '26 07:07

MrGeek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!