![](/img/trans.png)
[英]Looping through an array and setting each element as a property of an object messes with the order
[英]Looping through each property values of each object in an array in JavaScript
如何遍歷數組中的每個對象屬性值? 我想在前端渲染之前清理所有值。
sampleData = [
{ "Name": "<p>John </p>", "Age": 23, "Student": false },
{ "Name": "Bruno", "Age": 20, "Student": true },
{ "Name": "David ", "Age": 30, "Student": false },
];
這是舊代碼:
this.sampleData.forEach((tableRow) => {
let column = Object.entries(tableRow);
column.forEach((value) => {
let cell;
cell = value[1];
if ((typeof cell !== 'boolean') && (cell !== null) && (typeof cell !== 'number')) {
cell = this.sanitizeString(cell);
}
console.log(cell);
});
});
PS 我正在使用 Papa parse 來解析 .csv 數據並且已經有了衛生方法。
對於那些可能面臨與上述相同任務的人,我使用以下代碼解決了它:
this.dataPreview = this.sanitizedArray(result.data);
sanitizedArray(row) {
Object.keys(row).forEach((key) => {
// Sanitize each field in this scope
return Object.keys(row[key]).forEach((column) => {
if ( (typeof row[key][column] !== 'boolean') && (row[key][column] !== null) &(typeof row[key][column] !== 'number') ) {
row[key][column] = this.sanitizeString(row[key][column]);
}
});
// End of sanitation
});
return row;
}
或使用我朋友的建議:
const updatedSampleData = sampleData.map((data) => ({ ...data, property: newValue }));
謝謝
我認為Sandhands可能是一個很好的解決方案。 這是一個示例,說明如何在少量代碼中一次驗證所有數據
const {sanitize} = require('sandhands')
sanitize(sampleData, [{Name: {_: String, trimmed: true}, Age: {_: Number, min: 1}, Student: Boolean}]) // throws if the sample data is not properly formatted
披露:我寫了 Sandhands,但它是免費和開源的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.