Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
循环遍历数据,使用JavaScript创建具有键/值对的字典_Javascript_Json_Javascript Objects_Rows - Fatal编程技术网

循环遍历数据,使用JavaScript创建具有键/值对的字典

循环遍历数据,使用JavaScript创建具有键/值对的字典,javascript,json,javascript-objects,rows,Javascript,Json,Javascript Objects,Rows,我试图修改一些Javascript代码,从每一行创建对象,并为这些对象分配相应的键/值对。我一直没能弄明白这一点 我的电子表格如下所示: Persons name surname profession ID Sally Sally Smith Developer ID John John Appleseed Accountant 我所实现的是创建这样的对象,但正如您所看到的,第一个对象具有电子表格中最后一行的属性: ex

我试图修改一些Javascript代码,从每一行创建对象,并为这些对象分配相应的键/值对。我一直没能弄明白这一点

我的电子表格如下所示:

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.`);
    }
});
//查找密钥开始单元格并生成人员ID数组
const personIDs=[];
设HeaderRownNumber=0;
sheetData.forEach((行,行号)=>{
if(行[0]==config.personKeysStartCell){
HeaderRownNumber=行数;
设i=1;
对于(设i=1;i{
数据推送(i);
});
const personDomNames=数据[0];
sheetData.forEach((行,行号)=>{
如果(行[0]&&rowNumber>headerRowNumber){
for(人形常量){
for(设i=1;i{
如果(错误){
console.log(错误);
返回;
}否则{
log(`${filePath}已生成。`);
}
});
我非常感谢你的帮助。 提前谢谢

  • 您希望按如下方式转换以下电子表格值

    [
      ["Persons","name","surname","profession"],
      ["ID Sally","Sally","Smith","Developer"],
      ["ID John","John","Appleseed","Accountant"]
    ]
    
    • 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=[[“个人”、“姓名”、“姓氏”、“职业”]、[“萨莉身份证”、“萨莉”、“史密斯”、“开发者”]、[“约翰身份证”、“约翰身份证”、“苹果身份证”、“会计身份证”];
//用于将值从电子表格转换为字典的示例脚本。
var header=sheetData.shift();
header.shift();
var字典=sheetData.reduce(函数(obj1,行){
var value=row.shift();
obj1[值]=收割台.减少(功能(obj2,f,j){
obj2[f]=行[j];
返回obj2;
}, {});
返回obj1;
}, {});
console.log(字典);
//将每个字典写入其自己的es6模块文件
让personArray=[];
for(字典中的const person){
让output=`export const${person}={\n`;
for(字典中的常量键[人]){
常量值=字典[人][键];
if(值&&isNaN(值)){
输出+=`${key}:“${value}”,\n`;
}如果(!isNaN(值)&&value!==“”),则为else{
输出+=`${key}:${value},\n`;
}否则{
输出+=`${key}:未定义,\n`;
}
}
输出+=`};\n\n`;
personArray.push(输出);
}

控制台日志(personArray)如何读取电子表格范围?我是从config.js文件中获取的,该文件已正确设置为@Rubén@ale_aalt谢谢你的回复。我很高兴你的问题解决了。