Let's say I receive a JSON-string containing information about people. Now I loop through all the JSON-objects and extract the name and age or each person.
How would I store these as tuples in a list for further processing? (E.g. by another function)
Tuples are a sort of list but with a limited set of items. In JavaScript, tuples are created using arrays. In Flow you can create tuples using the [type, type, type] syntax.
Tuples are ordered lists of finite length that can be used as implicit key/value stores. While JavaScript doesn't have a Tuple yet (there is a TC39 proposal to add it), you might already be using them. You may find them useful for particular algorithms, writing custom hooks and more.
However, JavaScript objects have one fatal flaw: they're not properly iterable, in the sense of preserving “insertion order.” In other words, objects don't remember the order that object keys were added in.
In JavaScript, an array is a data structure that contains list of elements which store multiple values in a single variable. The strength of JavaScript arrays lies in the array methods.
Assuming the incoming JSON is something like the following:
var incomingList = [{ "name": "Homer Simpson", "age": 45, "occupation": "Nuclear Plant Technician", ... },{ "name": "Marge Simpson", "age": 44, "occupation": "Homemaker", ... }, ... ]
You could extract the name and age only into a similar array of objects:
var nameAndAgeList = incomingList.map(function(item) { return { name: item.name, age: item.age }; });
JavaScript only has objects and arrays, not tuples. If your data is associative (each record has key-value-pairs with the field name as the key) then the above approach will work fine.
However, if you need to associate the names and ages in a single object as key-value-pairs (like an associative array) with names as keys and ages as values, the following will work (assuming the names are unique):
var namesAndAges = incomingList.reduce(function(result,item) { result[item.name] = item.age; return result; },{});
Building on Vikram's answer, as you have specifically asked for tuples, the following returns you an array of arrays - in other words, a list of tuples.
var parsed = JSON.parse('[{"name":"john", "place":"usa", "phone":"12345"},{"name":"jim", "place":"canada", "phone":"54321"}]'); var people = []; for (var i=0; i < parsed.length; i++) { var person = [parsed[i].name, parsed[i].place, parsed[i].phone]; people.push(person); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With