Extract Array Data in Javascript

Asked

Viewed 554 times

1

I own a array with the working groups that the session user belongs to, for example if I write like this:

return $data.teste02[0].group_id.name

It returns me the first group that this user belongs to, which in this case would be administrator But there are cases that the session user will belong to more than one group, and I need to know all the working groups that he belongs to, so I thought I’d make a for to be able to access all the groups, thinking about it I made the following code:

for (var x = 0; x <= $data.teste02.length; x++){
   return $data.teste02[x].group_id.name;
}

But even so it only returns me the working group of the first position. If you have any idea how I can achieve that.

3 answers

3


When giving a Return inside a for, it implicitly applies a break then its repeating structure described above will stop at the first interaction.

It is very common to use this if you are looking for a specific value, or will give a binary return.

Then, as it is possible to have multiple groups, the solution is to accumulate in another array and return only the group names.

var grupos = [];
for (var x in $data.teste02){
   grupos.push($data.teste02[x].group_id.name);
}
return grupos ;

With this you could validate if the user is in a group using the method index for example.

if(grupos.indexOf('administrador') != -1){
  //Grupo administrador
}
  • Perfect, the idea of adding in another array worked perfectly. As soon as it becomes available I mark your answer as correct.

3

If you want to create a new array with the names you can use .map() thus:

var grupos = $data.teste02.map(el => el.group_id.name);

So you get a new array, with the same size but only with group_id.name.

  • For some reason the for is even more performative than map: https://jsperf.com/map-vs-for-loop-performance/6

  • 2

    @Leonancarvalho for me gives me that .map() is faster (https://snag.gy/H2kqoR.jpg). But in this case the question of semantics also makes me prefer the .map(), because we are exactly mapping data.

  • According, if the goal is just to map a certain data yes. But I’ve seen programmers use map for logical and conditional operations for laziness to mount a for rs

  • 1

    And semantics is all in one code...

3

This is a new technology, part of the Ecmascript 2015 (ES6) standard.

As a matter of curiosity, using generators is also possible to do basically following its logic. See an example:

function* get_group_names(data)
{
    for (let group of data.teste2) {
        yield group.group_id.name;
    }
}

Or, alternatively, as commented by Sérgio, use {group_id} in the for, which is the equivalent of group.group_by of the previous code:

function* get_group_names(data)
{
    for (let {group_id} of data.teste2) {
        yield group_id.name;
    }
}

This way, to get the list of group names, just convert the generator to array:

const groups = Array.from(get_group_names($data));

Or even travel it through a loop of repetition:

for (let group of get_group_names($data)) {
    console.log(group);
}

References:

Function* - Javascript | MDN

for...of - Javascript | MDN

How Yield* works in Javascript?

See working below.

const $data = {
  'teste2': [{
    'group_id': {
      'name': 'Grupo 1'
    },

  }, {
    'group_id': {
      'name': 'Grupo 2'
    },

  }, {
    'group_id': {
      'name': 'Grupo 3'
    },

  }]
};

function* get_group_names(data) {
  for (let group of data.teste2) {
    yield group.group_id.name;
  }
}

// Converte o gerador para array:
console.log(Array.from(get_group_names($data)));

// Ou percorre o gerador com um laço de repetição:
for (let group of get_group_names($data)) {
  console.log(group);
}

  • 1

    +1 by the generators. And it could even be for (let {group_id} of data.teste2) yield group_id.name; But I still prefer .map() in this case.

  • Very interesting the generator(+1), the problem is compatibility with legacy browsers. Safari already supports yield ?

  • @Leonancarvalho Apparently, yes: https://caniuse.com/#feat=es6-generators

Browser other questions tagged

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