I’m working in Typescript.
If I have an object about which I know nothing, how could I obtain
from that object a list of all the fields which have the name of, say,
"speed". (Clearly the answer would be null if there were no such entries).
I could JSON.stringify and write my own parsing, but was wondering if there was another way.
So, for example, my object might be:
MyObject = {AnEntry:{"speed":"5", "somthingElse":6},
AnotherEntry:{"somethingElse":"3"},
YetAnother:true,
AndMore:{"speed":"eleven"},
Finally:{"more":7,nested:{"notHere":7, "speed":"5"}}};
So, in this case, I would like query MyObject and return [5,"eleven"]
I’ve EDITED: Add = sign and updated object to show that I want to be able to cope with possibly nested objects.
3
Answers
After your Edit
To get nested prop "speed" values, use a recursive function like:
to get a unique set of values, reduce into a
new Set
:To get an array of the filtered fields where
speed
property (key) exists you could use:To get only an Array of the values use:
To get only unique values, use
new Set()
Docs:
Assuming you know nothing about the object, the "speed" attributes might be nested at multiple depths within your object. You can use recursion to traverse the tree of nested children to reach all of them.
Result: