gpt4 book ai didi

javascript - 将数组转换为JavaScript中的对象

转载 作者:行者123 更新时间:2023-12-01 16:14:27 25 4
gpt4 key购买 nike

我正在尝试在不支持ES6的Google表格应用脚本中对大量数据进行排序! (我认为)

数组看起来像这样
var data = [[“” Frank“,” franck@gmail.com“,21],[” Mark“,” Mark@gmail.com“,23]]

我很喜欢将数组变成对象的想法,在这里我可以通过ex名称访问每个对象:

Frank.name
Frank.email
Frank.age

我尝试了以下
function Driver(name, email, age) {
this.name= name;
this.email= email;
this.age = age;
}

然后
for(var i=0; i<data.length; i++){
data[i][0]= new Driver (data[i][0],data[i][1],data[i][2])
}

但这不起作用
你能帮我吗?

最佳答案

如果我了解您的要求

我很喜欢将数组变成对象的想法,可以在其中按名称访问每个对象

正确,那么解决方案就是这样简单:

ES6版本

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版本:

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)


警告:
如果必须在 name数组中使用具有相同 data的Divers,则将其中之一放开。

关于javascript - 将数组转换为JavaScript中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59830230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com