Suppose I have two arrays like these:
const dataset = [{n: "2", s: 'hello', b: 'TRUE'}, {n: "0", s: 'meow', b: 'FALSE'}]
const info = {n:{type: 'TEXT'}, s:{type: 'PARAGRAPH'}, b:{type: 'CHECKBOX'}}
and I want to transform dataset in this:
const dataset = [{n: 2, s: 'hello', b: true}, {n: 0, s: 'meow', b: false}]
so values with key n become numbers, values with key s became stringa and values with key b became booleans.
So I created this function to match info type and the key:
function dataType(formType) {
switch (formType) {
case 'TEXT':
return 'number'
case 'PARAGRAPH':
return 'string'
case 'CHECKBOX':
return 'boolean'
default:
throw new Error(`Something went wrong.`)
}
}
Now I need a function that parse dataset, check each object and transform all the values. I prefer to make a copy of dataset, so immutability.
I think to use a reduce but I need help:
function dataParse(dataset, info) {
const result = dataset.map((datum) => {
return Object.entries(datum).reduce((acc, curr, i) => {
// ???
return acc
}, {})
})
return result
}
I suppose to use a code similar to:
let v // don't like let
switch (value) {
case 'number':
v = +response
break
case 'string':
v = response.toString()
break
case 'boolean':
v = v === 'TRUE' ? true : false
break
default:
throw new Error(`Something went wrong.`)
but how?
The complete code is here:
function dataType(formType) {
switch (formType) {
case 'TEXT':
return 'number'
case 'PARAGRAPH':
return 'string'
case 'CHECKBOX':
return 'boolean'
default:
throw new Error(`Something went wrong.`)
}
}
function dataParse(dataset, info) {
const result = dataset.map((datum) => {
return Object.entries(datum).reduce((acc, curr, i) => {
// ???
return acc
}, {})
})
return result
}
const dataset = [{n: "2", s: 'hello', b: 'TRUE'}, {n: "0", s: 'meow', b: 'FALSE'}]
const info = {n:{type: 'TEXT'}, s:{type: 'PARAGRAPH'}, b:{type: 'CHECKBOX'}}
console.log(dataParse(dataset, info))