A list of tuples in Javascript [closed] A list of tuples in Javascript [closed] javascript javascript

A list of tuples in Javascript [closed]


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);}


JS doesn't have a "tuple" type of object. (see: JavaScript Variable Assignments from Tuples)

You can either create your own tuple-class or simply use an array of length 2 (so you end up with an array of length 2 arrays)