通过for循环创建对象

时间:2020-10-24 19:15:16

标签: javascript

我有这样的代码:

 var HardCodeObject = {
  title: "Customers",
  rows: [
    {
      cells: [
        { value: "Company Name" },
        { value: "Contact" }
      ]
    },
    {
      cells: [
        { value: "Around the Horn" },
        { value: "Thomas Hardy" }
      ]
    },
    {
      cells: [
        { value: "B's Beverages" },
        { value: "Victoria Ashworth" }
      ]
    }
  ]
};

如何通过Cells对象中的for循环创建此对象?

我尝试使用此代码,但不起作用:

var cells = [];
var value = new Array();
value.push("a");
value.push("b");
cells.push(value);
var value = new Array();
value.push("a");
value.push("b");
cells.push(value);
var value = new Array();
value.push("a");
value.push("b");
cells.push(value);
var d = new Object();
d.title = "Customer";
d.rows = cells;

用于在kendo UI中导出到excel。

2 个答案:

答案 0 :(得分:1)

有一个更好的方法来实现这一目标。首先,正如Samathingamajiga comment中所说的那样,请勿重复使用var关键字。

对于这个答案,我假设或要求您以以下形式在多维Elements数组中制作行的内容:

var Elements = [
  ["Company Name", "Contact"],              // Row 1
  ["Around the Horn", "Thomas Hardy"],      // Row 2
  ["B's Beverages", "Victoria Ashworth"]    // Row 3
];

其次,了解JavaScript基础将对您有很大帮助。让我在此处添加一个指导性答案:

// Create a new object by using an Object Literal.
var CodedObject = {};
// Set the title.
CodedObject.title = "Customers";
// Initialise rows with an empty array.
CodedObject.rows = [];
// Let's think of a couple of elements in a 2D Array.
var Elements = [
  ["Company Name", "Contact"],              // Row 1
  ["Around the Horn", "Thomas Hardy"],      // Row 2
  ["B's Beverages", "Victoria Ashworth"]    // Row 3
];
// Now let's use a loop to create objects based on the elements.
// Also, let's define a single Row Object.
var row = {};
for (var i = 0; i < Elements.length; i++) {
  // Reset the row object for every iteration.
  row = {
    cells: []
  };
  // Add the two values using a loop now.
  for (var r = 0; r < Elements[i].length; r++) {
    // Add cell value.
    row.cells.push({
      value: Elements[i][r]
    });
  }
  // Push the row value.
  CodedObject.rows.push(row);
}

// Let's see if this works.
console.log(CodedObject);

我得到上述程序的输出,如下所示:

{
  "title": "Customers",
  "rows": [
    {
      "cells": [
        {
          "value": "Company Name"
        },
        {
          "value": "Contact"
        }
      ]
    },
    {
      "cells": [
        {
          "value": "Around the Horn"
        },
        {
          "value": "Thomas Hardy"
        }
      ]
    },
    {
      "cells": [
        {
          "value": "B's Beverages"
        },
        {
          "value": "Victoria Ashworth"
        }
      ]
    }
  ]
}

答案 1 :(得分:0)

听起来您正在尝试执行以下操作:

const rows = [];
for (let i = 0; i < 3; i++) {
    rows.push({
        cells: [{
            value: "a"
        }, {
            value: "b"
        }]
    });
}

const obj = {
    title: "Customer",
    rows: rows
};

console.log(obj);

相关问题