entonces tengo un objeto JSON aquí:
// TableData { "0": { "damage_type": "Scratch", "regions": [ "front side", "back side" ], "price": 100 }, "1": { "damage_type": "Scratch", "regions": [ "front side", "back side, "right side" ], "price": 100 } }Y quiero convertirlo en algo como esto:
[ { "damage_type": "Scratch", "regions": "front side;\nback side", // Notice the array become a single string and separated with ; and \n "price": 100 }, { "damage_type": "Scratch", "regions": "front side;\nback side;\nright side", "price": 100 } ]Observe que la matriz se convierte en una sola cadena y se separa con ; y N
¿Alguien tiene alguna idea de cómo llegar a ese resultado?
Mi enfoque actual (y fallido):
Lo estoy haciendo un bucle así:
import data from '../data/table.json' const stringData = JSON.stringify(data) const tableData = JSON.parse(stringData) let processedData: any[] = [] for(var i = 0; i <= Object.keys(data).length - 1 ; i++){ processedData.push(tableData[i]) } console.log(processedData)Y el resultado sigue siendo así:
[ { "damage_type": "Scratch", "regions": ["Front Side", "Back side"], "price": 100 }, { "damage_type": "Scratch", "regions": ["Front Side", "Back side", "Right side"], // This part is still an array "price": 100 } ]Para que todo sea más fácil, vaya a https://onecompiler.com/javascript/3xb5y4qn8
La solución simple es usar Object.values y Array.map
const TableData = { "0": { "damage_type": "Scratch", "regions": [ "front side", "back side" ], "price": 100 }, "1": { "damage_type": "Scratch", "regions": [ "front side", "back side", "right side" ], "price": 100 } } const processedData = Object.values(TableData).map(row => ({ ...row, regions: row.regions.join(';\n'), })); console.log(processedData)Utilice el siguiente enfoque:
Object.values(TableData).map((item) => { return {...item, regions: item.regions.join(';\n')}; });