gpt4 book ai didi

javascript - 将嵌套数组转换为对象数组问题

转载 作者:行者123 更新时间:2023-11-30 06:20:18 25 4
gpt4 key购买 nike

我正在尝试将此嵌套数组数据转换为对象数组。这是数据。

  const tableData = [
["first_name", "last_name", "city", "state"],
["June", "Gregory", "Hammond", "IN"],
["James", "Wynn", "Gary", "IN"],
["Craig", "Norman", "Schererville", "IN"]
]

输出应该是这样的

[
{ first_name : "June", last_name : "Gregory", city: "Hammond", state : "IN" },
{ first_name : "James", last_name : "Wynn", city: "Gary", state : "IN" },
{ first_name : "Craig", last_name : "Norman", city: "Schererville", state : "IN" }
]

这是我的代码。

    function convertTable(table_data) {
var result = []
var key, value
for (var i=0; i<table_data.length; i++) {
var employee = {}
for (var j=0; j<table_data[i].length; j++) {
key = table_data[i][j][0]
value = table_data[i][j][1]
employee[key] = value
}
result.push(employee)
}
return result
}

var input = [
["first_name", "last_name", "city", "state"],
["June", "Gregory", "Hammond", "IN"],
["James", "Wynn", "Gary", "IN"],
["Craig", "Norman", "Schererville", "IN"]
]

console.log(convertTable(input));

解决方案是打印单词的第一个字母而不是整个单词。我很难理解为什么。我问是否有任何评论者可以逐行发表评论,以帮助我理解这个程序。我是在研究类似问题的帮助下写的,但仍然很难理解。我一直在 w3schools、MDN 上阅读有关 Javascript 的内容,并观看 Youtube 上的解释视频。任何其他帮助将不胜感激,谢谢。

最佳答案

试试这个,

你只是放错了一些索引,但一切都很好。只需与您的功能相匹配,您就可以轻松找到您错过的地方。

  const tableData = [
["first_name", "last_name", "city", "state"],
["June", "Gregory", "Hammond", "IN"],
["James", "Wynn", "Gary", "IN"],
["Craig", "Norman", "Schererville", "IN"]
]


function convertTable(table_data) {
var result = []
var key, value
for (var i=1; i<table_data.length; i++) {
var employee = {}
for (var j=0; j<table_data[i].length; j++) {
key = table_data[0][j]
value = table_data[i][j]
employee[key] = value
}
result.push(employee)
}
return result
}

var input = [
["first_name", "last_name", "city", "state"],
["June", "Gregory", "Hammond", "IN"],
["James", "Wynn", "Gary", "IN"],
["Craig", "Norman", "Schererville", "IN"]
]

console.log(convertTable(input));
  { first_name : "June", last_name : "Gregory", city: "Hammond", state : "IN" },
{ first_name : "James", last_name : "Wynn", city: "Gary", state : "IN" },
{ first_name : "Craig", last_name : "Norman", city: "Schererville", state : "IN" }
] */

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

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