![](/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.