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?
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);
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