How to separate items from an object array by dynamic types?

Asked

Viewed 354 times

-3

How do I separate items from one array of objects by a type that each object has? Remembering that types are known only at runtime.

For example:

[
    {
        id:1,
        name: maria,
        tipo: pessoa
    },
    {
        id:1,
        name: joao,
        tipo: pessoa
    }
]

and be able to print in this way:

pessoa: maria
        joao

and so on, in the picture shows a json how are my data.

inserir a descrição da imagem aqui

  • Do you want to print or separate each position into a variable? got confused your question?

  • So what happens, I have this object array where inside I can have several objects with various types, I’m actually displaying it with a . map, but now I need you to print the type above and the items of that type below

  • you have to pass the variable which I think is an object array of objects, I’m guessing?

  • That, even, more I have no idea how to do it, I would have some idea?

  • pastes a console.log image onto the variable

  • friend to without understanding, currently I do so , array.map(item => (<Text>{item.name}</Text>)), as I would now do?

  • isn’t having satisfactory result doing so? if you are using React? could put all the code?

  • I succeed with that code, understand? just wanted to list now in a new way, putting up the name of the type as I explained in the question above

  • Are you in doubt then on presentation of the result? and want to show all names under each other?

Show 4 more comments

2 answers

2

You have to remake the object

var a = [
  {
    id: 1,
    name: 'maria',
    tipo: 'pessoa',
  },
  {
    id: 1,
    name: 'joao',
    tipo: 'pessoa',
  },
  {
    id: 1,
    name: 'tareco',
    tipo: 'animal',
  },
];
var b ={};
for (var i = 0; i < a.length; i++) {
  if (a[i].tipo) {
    if (!b[a[i].tipo]) {
      
      b[a[i].tipo] = [];
    }
    b[a[i].tipo].push(a[i]);
  }
}
console.log(b);

  • 1

    worked friend that way

  • Thank you @Joycinha. Please mark as the answer is correct.

1


Use the filter to check each item, and choose by type (or other property) You must pass a callback, which will check each element of the array. If this callback returns true, the element will be returned in a new array.


let array = [
    {
        id:1,
        name: 'maria da silva',
        tipo: 'pessoa'
    },
    {
        id:2,
        name: 'joao',
        tipo: 'pessoa'
    },
    {
        id:3,
        name: 'maria de souza',
        tipo: 'pessoa'
    },
    {
        id:4,
        name: 'toto',
        tipo: 'animal'
    }
]

// 'i' é o ítem, pode ter qualquer nome
let pessoas = array.filter((i) =>{
        return i.tipo == 'pessoa'
    })


let animais = array.filter((i) => {
        return i.tipo == 'animal'
    })

let marias = array.filter((i) => {
        return i.name.indexOf('maria') >= 0;
})
   
console.log(pessoas);

/* resultado do console.log acima
[{
  id: 1,
  name: "maria da silva",
  tipo: "pessoa"
}, {
  id: 2,
  name: "joao",
  tipo: "pessoa"
}, {
  id: 3,
  name: "maria de souza",
  tipo: "pessoa"
}] */

console.log(animais);

/* resultado do console.log acima
[{
  id: 4,
  name: "toto",
  tipo: "animal"
}]
*/

console.log(marias)

/* [{
  id: 1,
  name: "maria da silva",
  tipo: "pessoa"
}, {
  id: 3,
  name: "maria de souza",
  tipo: "pessoa"
}] */


let a =[{
        id:1,
        name: 'maria da silva',
        tipo: 'personagem'
    },
    {
        id:2,
        name: 'joao',
        tipo: 'pessoa'
    },
    {
        id:3,
        name: 'maria de souza',
        tipo: 'pessoa'
    },
    {
        id:4,
        name: 'toto',
        tipo: 'animal'
    }
]


//acrescentado após comentário explicando que os tipos são dinâmicos

let tipos = a.map((i) => {
    return i.tipo;
})

console.log (tipos)

/*
resultado do console.log acima
["personagem", "pessoa", "pessoa", "animal"]
 */
 
r = {};
  
  
tipos.forEach((t) => {
  r[t] = a.filter((i)=>{
    return i.tipo == t;
  })
});


console.log(r);
/* 
resultado, separado por tipo
{
  animal: [{
  id: 4,
  name: "toto",
  tipo: "animal"
}],
  personagem: [{
  id: 1,
  name: "maria da silva",
  tipo: "personagem"
}],
  pessoa: [{
  id: 2,
  name: "joao",
  tipo: "pessoa"
}, {
  id: 3,
  name: "maria de souza",
  tipo: "pessoa"
}]
}
*/
  • just because I can’t do it this way because I won’t know what kind will come in the array, how many types will come, so I can’t control what kind will come

  • You can yes... You can for example extract all types before, then go through them.. Take a look here: https://jsfiddle.net/Lpvkt1qw/

  • 1

    I put the same code in the answer, to make both strategies available.

  • 1

    show, funcionoou

  • Good... remember to accept the answer ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.