Search code examples
javascriptnode.jsarraystypescriptobject

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'
    },
]

Solution

  • Just a simple for loop is probably the clearest. Here storing each object in a temp variable to avoid having to access the end of the result array every iteration, and abstracting the size into a variable.

    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' },];
    
    const size = 3;
    const result = [];
    
    for (let temp, i = size; i < data.length; i++) {
      if (i % size === 0) {
        result.push(temp = {});
      }
      temp[data[i % size].text] = data[i].text;
    }
    
    console.log(result)