循环遍历数据以使用 JavaScript 创建具有 key/value 对的字典

Loop through data to create a dictionary with key/value pairs using JavaScript

我正在尝试修改一些 Javascript 代码以从每一行创建对象并将这些对象分配给它们对应的 key/value 对。我还没弄明白。

我的电子表格如下所示:

Persons      name    surname      profession
ID Sally     Sally   Smith        Developer
ID John      John    Appleseed    Accountant

我实现的是像这样创建对象,但如您所见,第一个对象具有电子表格中最后一行的属性:

export const id_sally = {
    name: "John",
    surname: "Appleseed",
    profession: "Accountant"
};

export const id_john = {
    name: "John",
    surname: "Appleseed",
    profession: "Accountant"
};

代码如下:

// Find Keys start cell and build array of Person IDs
const personIDs = [];
let headerRowNumber = 0;
sheetData.forEach((row, rowNumber) => {
    if (row[0] === config.personKeysStartCell) {
        headerRowNumber = rowNumber;
        let i = 1;
        for (let i = 1; i < sheetData.length; i++) {
            // Here sheetData[i][0] refers to all the DOM names of the persons
            let personName = sheetData[i][0];
            personIDs.push({
                name: personName.toLowerCase(),
                columnIndex: i
            });
        }
    }
});

// Build a dictionary of key/value pairs for each personID
const dictionary = {};
for (const person of personIDs) {
    dictionary[person.name] = {};
}

const data = [];

sheetData.forEach(i => {
    data.push(i);
});

const personDomNames = data[0];

sheetData.forEach((row, rowNumber) => {
    if (row[0] && rowNumber > headerRowNumber) {
        for (const ad of personIDs) {
            for (let i = 1; i < personDomNames.length; i++) {
                dictionary[person.name][personDomNames[i]] = row[i];
            }
        }
    }
});

// Write each dictionary to its own es6 module file
let personArray = [];
for (const person in dictionary) {
    let output = `export const ${person} = {\n`;
    for (const key in dictionary[person]) {
        const value = dictionary[person][key];
        if (value && isNaN(value)) {
            output += `    ${key}: "${value}",\n`;
        } else if (!isNaN(value) && value !== "") {
            output += `    ${key}: ${value},\n`;
        } else {
            output += `    ${key}: undefined,\n`;
        }
    }
    output += `};\n\n`;
    personArray.push(output);
}
const filePath = `${config.outputDir}/personsInventory.js`;
fs.writeFile(filePath, personArray.join(""), error => {
    if (error) {
        console.log(error);
        return;
    } else {
        console.log(`${filePath} generated.`);
    }
});

非常感谢您的帮助。 提前致谢!

  • 您想按如下方式转换以下电子表格值。

    • 来自

      Persons name    surname profession
      Sally   Sally   Smith   Developer
      John    John    Appleseed   Accountant
      
    • {
        "ID Sally": {"name": "Sally", "surname": "Smith", "profession": "Developer"},
        "ID John": {"name": "John", "surname": "Appleseed", "profession": "Accountant"}
      }
      
  • 您想使用 Node.js 实现此目的。

  • 您已经能够从电子表格中获取值。

    • 您脚本中sheetData的值如下。

      [
        ["Persons","name","surname","profession"],
        ["ID Sally","Sally","Smith","Developer"],
        ["ID John","John","Appleseed","Accountant"]
      ]
      

如果我的理解是正确的,这个答案怎么样?请将此视为几个可能的答案之一。

示例脚本:

var sheetData = [["Persons","name","surname","profession"],["ID Sally","Sally","Smith","Developer"],["ID John","John","Appleseed","Accountant"]];

// Sample script for converting the values from Spreadsheet to a dictionary.
var header = sheetData.shift();
header.shift();
var dictionary = sheetData.reduce(function(obj1, row) {
  var value = row.shift();
    obj1[value] = header.reduce(function(obj2, f, j) {
    obj2[f] = row[j];
    return obj2;
  }, {});
  return obj1;
}, {});
console.log(dictionary);


// Write each dictionary to its own es6 module file
let personArray = [];
for (const person in dictionary) {
    let output = `export const ${person} = {\n`;
    for (const key in dictionary[person]) {
        const value = dictionary[person][key];
        if (value && isNaN(value)) {
            output += `    ${key}: "${value}",\n`;
        } else if (!isNaN(value) && value !== "") {
            output += `    ${key}: ${value},\n`;
        } else {
            output += `    ${key}: undefined,\n`;
        }
    }
    output += `};\n\n`;
    personArray.push(output);
}
console.log(personArray);

  • 在上面的示例脚本中,dictionary 可用于您脚本中的 dictionary

如果我误解了您的问题而这不是您想要的结果,我深表歉意。届时,您能否提供您期望的示例输入输出值?至此,我想修改一下。