With the reduce
function of JavaScript you get this result.
See the live example here: link
As you explained, your data set is 3 items within the list. That is, every 3 items in the original list you put a new item in the new list.
// Dados recebidos.
const dados = [ "calças", "XXS", "16", "fita", "M", "13", "calças", "XXS", "1" ];
// Total de itens que compõem um conjunto
const conjunto = 3;
//Nova lista
const dadosMapeados = dados.reduce((val, cur) => {
if (val.length === 0 || val[val.length - 1].length === conjunto) val.push([]);
val[val.length - 1].push(cur);
return val;
}, []);
The result for dadosMapeados
will be this:
[
["calças", "XXS", "16"],
["fita", "M", "13"],
["calças", "XXS", "1"]
]
If you need to use JSON instead of ARRAY , use the map
JavaScript function on top of the result. But you need to ensure that the array has enough elements or make a check by switching item[0]
to item.length > 0 ? item[0] : null
in the example below.
dadosMapeados = dadosMapeados.map(item => { return {
nome: item[0],
tipo: item[1],
tamanho: item[2]
}});
Now, the result for dadosMapeados
will be this:
{
{nome: "calças", tipo: "XXS", tamanho: "16"},
{nome: "fita", tipo: "M", tamanho: "13"},
{nome: "calças", tipo: "XXS", tamanho: "1"}
}