Я пытаюсь изменить некоторый код 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.`);
}
});
Буду признателен за помощь здесь. Заранее спасибо!