so I have a JSON object here:
// 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
}
}
And I want to convert it to something like this:
[
{
"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
}
]
Notice the array become a single string and separated with ; and \n
Does anybody have any idea how to reach that result?
My current (and unsuccessful) approach:
I am looping it like this:
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)
And the result is still like this:
[
{
"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
}
]
To make everything easier please go https://onecompiler.com/javascript/3xb5y4qn8
Simple solution is using Object.values and 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)
Use following approach:
Object.values(TableData).map((item) => {
return {...item, regions: item.regions.join(';\n')};
});