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

3
我正在尝试将这个嵌套的数组数据转换成对象数组。以下是数据:

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

解决方案是打印单词的第一个字母而不是整个单词。我很难理解为什么要这样做。我希望评论者能够逐行留下评论,以帮助我理解这个程序。我在查找类似问题的过程中得到了帮助,但仍然很难理解。我一直在阅读关于JavaScript的w3schools、MDN和观看Youtube视频的解释。任何其他帮助将不胜感激,谢谢。

请看一下这个链接:https://stackoverflow.com/help/someone-answers。如果答案对您有帮助,请注意遵循这些建议。请记住,人们花费时间和精力来帮助您,并且会很感激您的反馈。下面有一些不错的答案... - undefined
5个回答

0
这是使用Array.reduce的简洁版本:

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

const result = data.reduce((r,c,i,arr) => {
  if(i) r.push(c.reduce((a,b,j) => (a[arr[0][j]] = b, a), {}))
  return r
}, [])
console.log(result)

这个想法是跳过第一行/标题行,然后继续将内部reduce组成的对象推送到累加器中,该对象简单地使用标题(作为键)和当前数组(作为值)的值进行装饰。


-1,不够减少;) - undefined
:) 有没有所谓的“足够减少”这种东西? - undefined

0
试试这个,

You just misplaced some index except that everything is fine. Just match with your function and you can find easily where you missed.

  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" }
] */


0

你的代码有三个错误,可以按照以下方式修复:

  1. i = 1 开始迭代外部循环,跳过索引为 0 的标题。

  2. 使用 tableData[0][j] 而不是 tableData[i][j][0] 来索引标题数组,后者维度过多(访问字符)并且错误地包含了行索引 i

  3. 使用 tableData[i][j] 而不是 tableData[i][j][1] 来索引数据表,后者再次访问了字符串中的字符。

除此之外,我建议注意空格、分号和驼峰命名规范。这将使你的代码更易于理解和调试。

将它们整合起来得到:

function convertTable(tableData) {
  var result = [];
  var key;
  var value;
  
  for (var i = 1; i < tableData.length; i++) { // start at 1 to skip headers
    var employee = {};
    
    for (var j = 0; j < tableData[i].length; j++) {
      key = tableData[0][j];   // remove character index and use [0][j]
      value = tableData[i][j]; // remove character index
      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));

此外,这是一个非常适合使用数组函数mapreduce来执行CSV到对象转换的任务。shift()将标题从数组前面弹出,map循环遍历行并对每一行应用reducereduce使用ij行/列索引以与您的函数相同的方式引用标题数组来构建对象。

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

const headers = tableData.shift();
const result = tableData.map((e, i) => 
  e.reduce((a, f, j) => {
    a[headers[j]] = f;
    return a;
  }, {})
);

console.log(result);


0
你正在访问一个根数组的3级深度,所以你在索引2级数组中的字符串。
使用这个:key = table_data[i][j][0] 你正在访问索引为i的数组内第j个位置的字符串的第一个字符。
而使用这个:value = table_data[i][j][1] 你正在访问索引为i的数组内第j个位置的字符串的第二个字符。
此外,你已经知道第一个数组是键(或标题),所以你不想在它上面进行循环。请参考下一个示例:

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


0
首先,你为两个值都取了一个单字符,这是不必要的。
key = table_data[i][j][0]
//                    ^^^
value = table_data[i][j][1]
//                      ^^^

那么你需要做两个改变,一个是外层循环省略键,内部使用第一行作为键。请参考代码中的注释。

另一个改变是将所有变量声明在函数顶部。

function convertTable(table_data) {
    var result = [],
        key, value,
        employee,
        i, j;

    for (i = 1; i < table_data.length; i++) {        // start from index 1
        employee = {};
        for (j = 0; j < table_data[i].length; j++) {
            key = table_data[0][j];                  // take the value form index zero
                                                     // no following index for the letter
            value = table_data[i][j];                // no following index for the letter
            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));
.as-console-wrapper { max-height: 100% !important; top: 0; }

不同的方法

function convertTable(table) {
    return table
        .slice(1)
        .map(a => Object.assign(...table[0].map((k, i) => ({ [k]: a[i] }))));
}

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

console.log(convertTable(input));
.as-console-wrapper { max-height: 100% !important; top: 0; }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接