如何在 JavaScript 中将二维数组转换为二维对象?

how to convert 2d array to 2d object in JavaScript?

所以我试图通过 EJS 模板将一些 JSON 对象从 NODE 传递到客户端 JavaScript。我面临的问题是我无法从二维数组创建二维对象。下面的代码用于在 NODE 中将对象传递到 EJS 模板中:

let json_jobs = {};
let singleJSON = {};
let array_jobs = [
  ["aaaa", "title_1", "fulltime", "location1"],
  ["bbbb", "title_2", "parttime", "location2"],
  ["cccc", "title_3", "fulltime", "location3"],
  ["dddd", "title_4", "flex", "location4"]
];

for (let i = 0; i < array_jobs.length; i++) {
  singleJSON = {
    index: i,
    id: array_jobs[i][0],
    title: array_jobs[i][1],
    contract_type: array_jobs[i][2],
    location: array_jobs[i][3]
  }
  console.log(typeof(singleJSON ));
  console.log(singleJSON );
  
  json_jobs += {
    job: singleJSON[i]
  }
}
console.log(typeof(json_jobs));
console.log(json_jobs);

//return res.render('pages/searchJobs', {job_data: array_jobs});

问题是我无法使用 += 运算符添加推送对象,并且没有函数 push() 可用于 javascript 对象?有什么解决办法吗?

这就是我想要的最终对象:

    let json_jobs= {
      {
          job: {
              index: 0,
              id: "aaaa",
              title: "title1",
              contract_type: "fulltime",
              location: "location1"
          },
          job: {
              index: 1,
              id: "bbbb",
              title: "title2",
              contract_type: "parttime",
              location: "location2"
          },
          ....
      }

您可以解构行和 return 具有 short hand properties 的对象。

let array_jobs = [ ["aaaa", "title_1", "fulltime", "location1"], ["bbbb", "title_2", "parttime", "location2"], ["cccc", "title_3", "fulltime", "location3"], ["dddd", "title_4", "flex", "location4"]],
    result = array_jobs.map(([id, country, contract_type, location], index) =>
        ({ index, id, country, contract_type, location }));

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

job属性必须是数组才能存储多个对象

let json_jobs = {jobs: []};
let singleJSON = {};
let array_jobs = [
  ["aaaa", "title_1", "fulltime", "location1"],
  ["bbbb", "title_2", "parttime", "location2"],
  ["cccc", "title_3", "fulltime", "location3"],
  ["dddd", "title_4", "flex", "location4"]
];

for (let i = 0; i < array_jobs.length; i++) {
  singleJSON = {
    index: i,
    id: array_jobs[i][0],
    title: array_jobs[i][1],
    contract_type: array_jobs[i][2],
    location: array_jobs[i][3]
  }
  json_jobs.jobs.push(singleJSON);
}
console.log(json_jobs);