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.
Take a look at hugomg response or in the Sergio’s response or in that of Kaduamaral on that question I marked as duplicate.
– Victor Stafusa
@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
– Jefferson Quesado
I take this opportunity to say that the
flat
is also being incorporated intoArray
and that will do this directly in a function. Unfortunately the support at this time is very scarce, but even has a polyfill.– Isac
@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, withreduce
– Jefferson Quesado
@Isac, the reference of
flatMap
and from where I got the how to do viareduce
– Jefferson Quesado
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.
– Isac
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
– hugocsl