I have an array of objects with two properties: canais
and topicos
:
channel: Array(3)
0: {canais: 'canal1', topicos: 'topico1'}
1: {canais: 'canal2', topicos: 'topico2'}
2: {canais: 'canal3', topicos: 'topico3'}
I want to split into two array of strings called canais and topicos:
canais : [ "canal1" , "canal2", "canal3" ];
topicos: [ "topico1" , "topico2", "topico3" ];
CodePudding user response:
You can do
const canais = channel.map(item => item.canais)
const topicos = channel.map(item => item.topicos)
CodePudding user response:
You could do this in multiple ways:
Map each element to a 2-element array
[canais, topicos]
and then transpose the result to get two arrays (hereoriginal
is your array):const transpose = arr => arr[0].map((x, i) => arr.map(x => x[i])) const [canais, topicos] = transpose(original.map(a => [a.canais, a.topicos]))
See also: Transposing a 2D-array in JavaScript which is the origin of the
transpose
function above.Use a
forEach
loop and accumulate:const canais = [] const topicos = [] original.forEach(el => { canais.push(el.canais) topicos.push(el.topicos) })
Normal
for
loop and accumulate:const allCanais = [] const allTopicos = [] for (const {canais, topicos} of original) { allCanais.push(canais) allTopicos.push(topicos) }
Map two times (first extract all
el.canais
then allel.topicos
), though this iterates twice over the data which is probably unneeded.
CodePudding user response:
If you need it to be dynamic, you can use a nested for loop to go through each item and create/add to arrays based on the key, then use an object to store each array of values.
let channelNames = {};
for(let c of channel){
for(let key in c){
if(!channelNames[key])
channelNames[key] = [];
channelNames[key].push(i[key]);
}
}