簡體   English   中英

在 JavaScript 中循環遍歷數組中每個對象的每個屬性值

[英]Looping through each property values of each object in an array in JavaScript

如何遍歷數組中的每個對象屬性值? 我想在前端渲染之前清理所有值。

sampleData = [
    { "Name": "<p>John &nbsp;</p>", "Age": 23, "Student": false },
    { "Name": "Bruno", "Age": 20, "Student": true },
    { "Name": "David &nbsp;", "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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM