Is there an alternative in Javascript similar to Java 8’s "flatMap"?

Asked

Viewed 77 times

3

I need to do an element mapping that returns a vector to me. However, I am already doing a job on top of a array, then the simple map will return me a vector containing vectors.

In this case, I have a vector of non-homogeneous objects, varying field names and quantity; for example:

[
    {
        "cod": "1",
        "ds": "marmota 1"
    },
    {
        "cod_2": "1",
        "ds": "marmota 2"
    },
    {
        "cod": "2",
        "descricao": "descritiva"
    },
    {
        "cod": "3",
        "descricao": "descritivamente",
        "payload": "baleia"
    }
]

I would like to be returned something like this:

[ "cod", "ds", "cod_2", "ds", "cod", "descricao", "cod", "descricao", "payload" ]

Or so (with elimination of duplicates):

[ "cod", "ds", "cod_2", "descricao", "payload" ]

This second case is not extremely important to me because I can use the Set to such an end

When trying to do the mapping used Object.keys(), I don’t get the desired result:

let dados = [ { "cod": "1", "ds": "marmota 1" }, { "cod_2": "1", "ds": "marmota 2" }, { "cod": "2", "descricao": "descritiva" }, { "cod": "3", "descricao": "descritivamente", "payload": "baleia" } ];

console.log(dados.map(l => Object.keys(l)));

but the result is a vector with vectors inside:

[ 
  ["cod","ds"] , 
  ["cod_2","ds"] , 
  ["cod","descricao"] , 
  ["cod","descricao","payload"] 
]

If I were using Java 8, it would be something like the operation of flatMap of streams. The equivalent of my desired result would be something like this:

List<Map<String, String>> dados = ...; // fica povoado como os dados adequados
Set<String> resultado = dados.stream().flatMap(m -> m.keySet().stream()).collect(Collectors.toSet());

The ideal, for me, in Javascript would be something that I could continue working as a stream Java 8. Actually, it still has some filter that I would like to do before collecting the final data.

  • 1

    Take a look at hugomg response or in the Sergio’s response or in that of Kaduamaral on that question I marked as duplicate.

  • @Victorstafusa , it seems that my question is just a special case of this one that you indicated. I was looking for something like Sergio’s (first excerpt, mainly). When I open the computer I mark as exact duplicate

  • 1

    I take this opportunity to say that the flat is also being incorporated into Array and that will do this directly in a function. Unfortunately the support at this time is very scarce, but even has a polyfill.

  • 1

    @Isac also has the flatMap which is on the way to being made official. It was there that I actually found a solution similar to Sergio’s, with reduce

  • @Isac, the reference of flatMap and from where I got the how to do via reduce

  • 1

    Yes, I suspect that whoever created one created the other as well, given the similarity and equal support. Until the alternative suggested reduce is equal.

  • 1

    I know the question has a little time but sometimes it may interest you flatMap - Functional Javascript - Supercharged: https://www.youtube.com/watch?v=qgrila9cbzg

Show 2 more comments

1 answer

-1


Using .reduce() with .forEach() will add key names of objects in the array res[]:

let dados = [ {"cod": "1", "ds": "marmota 1"}, {"cod_2": "1", "ds": "marmota 2" }, {"cod": "3", "descricao": "descritivamente" , "payload": "baleia"}];

const res = dados.reduce((i, e)=>{
   Object.keys(e).forEach(e=>{
      i.push(e);
   });
   return i;
}, []);

console.log(res);

  • It came close. Only it can be multiple keys, not just 2 per object. I’ll edit to clarify the question

  • I changed the code. []s

Browser other questions tagged

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