I'm trying to sort a big collection of data in google sheets app script which doesn't support ES6! (I think)
The array looks something like this var data = [["Frank", "franck@gmail.com", 21],["Mark", "Mark@gmail.com", 23]]
I would love the idea to turn the array into objects where I can access every object by the name ex:
Frank.name
Frank.email
Frank.age
I tried the following
function Driver(name, email, age) {
this.name= name;
this.email= email;
this.age = age;
}
and then
for(var i=0; i<data.length; i++){
data[i][0]= new Driver (data[i][0],data[i][1],data[i][2])
}
But it is not working Can You help me with this?
If I understand your requirement
I would love the idea to turn the array into objects where I can access every object by the name
correctly, then the solution is as simple as this:
ES6 Version
function Driver(name, email, age) { this.name= name; this.email= email; this.age = age; } const data = [["Frank","franksmail",2], ["name2", "mail2", 3], ["name3", "mail3", 4]] const mappedData = data //map the array of arrays to an array of Drivers .map(props => new Driver(...props)) //reduce the array of drivers to a single object .reduce((accumulator, currentDriver) => { accumulator[currentDriver.name] = currentDriver return accumulator }, {}) console.log(mappedData) console.log(mappedData.Frank.email)
ES5 Version:
function Driver(name, email, age) { this.name= name; this.email= email; this.age = age; } var data = [["Frank","franksmail",2], ["name2", "mail2", 3], ["name3", "mail3", 4]] var mappedData = data //map the array of arrays to an array of Drivers .map(function (props) { return new Driver(props[0], props[1], props[2]) }) //reduce the array of drivers to a single object .reduce(function (accumulator, currentDriver) { accumulator[currentDriver.name] = currentDriver return accumulator }, {}) console.log(mappedData) console.log(mappedData.Frank.email)
Warning:
If you have to Divers with the same name
in your data
array then you'll loose one of them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.