Is there any JavaScript alternative similar to the Java flatMap? [duplicate]

3

I need to do an element mapping that returns a vector. However, I'm already doing a job on top of a array , so 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 something like this to be returned to me:

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

Or so (with deletion of duplicates):

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

This second case is not extremely important to me, as I can use Set for this purpose

When trying to make the mapping used Object.keys() , I do not 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 flatMap fault of streams . The equivalent of my desired result would look 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 thing for me in JavaScript would be something I could continue working as a stream of Java 8. In fact, I still have some filter operations that I would like to do before collecting the final data.

    
asked by anonymous 30.07.2018 / 08:33

1 answer

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

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);
    
30.07.2018 / 09:28