Home > OS >  How to convert array to object and group by index number / steps in js
How to convert array to object and group by index number / steps in js

Time:11-20

I have an array

[
a1,
b1,
c1,
d1,
a2,
b2,
c2,
d2
]

and I would like to convert it to:

{
    0: {
        name: a1,
        tel: b1,
        mail: c1,
        address: d1
        },
    1: {
        name: a2,
        tel: b2,
        mail: c2,
        address: d2
        }
}

Basically group them every 4 array steps. What is the best way to do this?

Appreciate any help. Thank you

CodePudding user response:

I provide a solution by iteration,however I think deserialization is more better choice,waiting for more elegant solution

let data = [
`a1`,
`b1`,
`c1`,
`d1`,
`a2`,
`b2`,
`c2`,
`d2`
]

let keys = ['name','tel','mail','address']
let result = {}
for(let i=0;i<data.length;i=i keys.length){
  result[i/4] = {}
  for(key of keys){
    result[i/4][key] = data[i]
  }
}
console.log(result)

CodePudding user response:

const d = ['a1','b1','c1','d1','a2','b2','c2','d2']

const f = ([name, tel, mail, address, ...rest]) =>
  [{name, tel, mail, address}, ...rest.length?f(rest):[]];

console.log(Object.fromEntries(f(d).map((e,i)=>[i,e])));

Or, without recursion:

const d = ['a1','b1','c1','d1','a2','b2','c2','d2']
const keys = ['name','tel','mail','address'];

console.log(d.reduce((a,c,i,r)=>(i%keys.length?0:a[i/keys.length|0]
  = Object.fromEntries(keys.map((k,j)=>[k,r[i j]])),a),{}));

  • Related