Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to construct an array of object to unique array of object

I have an array of object like this

let data = 
[
    {
        text: 'label'
    },
    {
        text: 'username'
    },
    {
        text: 'category'
    },
    {
        text: 'book'
    },
    {
        text: 'john'
    },
    {
        text: 'education'
    },
    {
        text: 'car'
    },
    {
        text: 'doe'
    },
    {
        text: 'automotive'
    },
    {
        text: 'shoes'
    },
    {
        text: 'cena'
    },
    {
        text: 'fashion'
    },
]

and my expect array of objects

let result = 
[
    {
        label: 'book',
        username: 'john',
        category: 'education'
    },
    {
        label: 'car',
        username: 'doe',
        category: 'automotive'
    },
    {
        label: 'shoes',
        username: 'cena',
        category: 'fashion'
    },
]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

According to your data,the top 3 records are property name,others are data,so we can use Array.slice() to get the property names

Then we can use Array.reduce() to convert the left data

let keys = data.slice(0,3).map(v => v.text)
let result = data.slice(3).reduce((a,c,i) =>{
  let key = keys[i%3]
  if(i%keys.length ==0){
   let obj = {}
   obj[key] = c.text
   a.push(obj)
  }else{
   a.at(-1)[key]=c.text
  }
  return a
},[])

console.log(result)
let data = 
[
    {
        text: 'label'
    },
    {
        text: 'username'
    },
    {
        text: 'category'
    },
    {
        text: 'book'
    },
    {
        text: 'john'
    },
    {
        text: 'education'
    },
    {
        text: 'car'
    },
    {
        text: 'doe'
    },
    {
        text: 'automotive'
    },
    {
        text: 'shoes'
    },
    {
        text: 'cena'
    },
    {
        text: 'fashion'
    },
]

let keys = Object.values(data.slice(0,3)).map(v => v.text)
let result = data.slice(3).reduce((a,c,i) =>{
  let key = keys[i%3]
  if(i%keys.length ==0){
   let obj = {}
   obj[key] = c.text
   a.push(obj)
  }else{
   a.at(-1)[key]=c.text
  }
  return a
},[])

console.log(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading