How can we make separate objects of unique keys? Below is the sample array:
var arr = [
{"name": "john"},
{"email": "[email protected]"},
{"phone": "2222222"},
{"name": "jack"},
{"email":"[email protected]"},
{"phone":"2222222333"}
]
Output:
[
{
{"name" :"john"},
{"email": "[email protected]"},
{"phone": "2222222"}
},
{
{"name": "jack"},
{"email": "[email protected]"},
{"phone": "2222222333"}
}
]
CodePudding user response:
I suppose you are looking for that ?
const data =
[ { name : 'john' }
, { email : '[email protected]' }
, { phone : '2222222' }
, { name : 'jack' }
, { email : '[email protected]' }
, { phone : '2222222333' }
]
const result = data.reduce((w,row,i,{[i 1]:next}) =>
{
let [key,val] = Object.entries(row)[0]
if (!i || w.el.hasOwnProperty(key) )
{
w.el = { [key]: val }
w.res.push(w.el)
}
else w.el[key] = val
return next ? w : w.res
}
, { res:[],el:null}
)
console.log( result )
.as-console-wrapper {max-height: 100%!important;top:0 }