Ivaylo Kostov
Ivaylo Kostov

Reputation: 13

Turn array into objects in javascript

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", "[email protected]", 21],["Mark", "[email protected]", 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?

Upvotes: 1

Views: 99

Answers (1)

Wendelin
Wendelin

Reputation: 2401

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.

Upvotes: 5

Related Questions