Let's say we have two arrays defined as:
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 the goal is to convert dataset
into the following format:
const dataset = [{n: 2, s: 'hello', b: true}, {n: 0, s: 'meow', b: false}]
where values with key n
are transformed into numbers, those with key s
into strings, and with key b
into booleans.
A function was created to match the type in info
with the corresponding 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 a function is needed to check each object in dataset
, transform all the values according to the matching types in info
, while making a copy of the dataset for immutability purposes.
The idea is to use a reduce
method but some guidance is required:
function dataParse(dataset, info) {
const result = dataset.map((datum) => {
return Object.entries(datum).reduce((acc, curr, i) => {
// ???
return acc
}, {})
})
return result
}
An example of how to handle values could be like this:
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 would that work exactly?
The complete code snippet is provided below:
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))