This is more of a general question of both code and math. I'm not at all good at math, and I'm still learning how to apply math in programming.
Let's say, I have an object of data that has the amount, the measurement, and the type, such as feet
or lb
.
const data = {
0: {
'type': 'imperial',
'unit': 'ft',
'amount': 3
},
1: {
'type': 'imperial',
'unit': 'lb',
'amount': 5
},
2: {
'type': 'imperial',
'unit': 'mph',
'amount': 7
}
}
And I need to go through this data and convert each according to the type (assuming type is what it's called)
Object.keys(data).map(key => {
convert(data[key]['amount'], data[key]['type'], data[key]['unit'])
})
And the function converts this:
const convert = (amount, type, unit) => {
const calc = // ???
return calc;
}
My question is, how do I convert depending on the type of measurement? I know that 1 foot is 0.3048 meters, and if I needed to convert 5 feet to meters, I'd do 5*0.3048
.
However, how can I apply this in code, with a list of imperial and metric units and how would I add this to the convert function?
You can have a converter
Object with functions to convert and labels to display, here's an example ( adjust the values and units to your needs ):
const data = { 0: { type: "imperial", unit: "ft", amount: 3 }, 1: { type: "imperial", unit: "lb", amount: 5 }, 2: { type: "imperial", unit: "mph", amount: 7 } }; const converter = { imperialToMetric: { ft: val => val * 0.3048, lb: val => val * 0.453592, mph: val => val * 1.60934, labels: { ft: "meters", lb: "Kg", mph: "kmh" } }, metric: { // reverse the above } }; const result = Object.values(data).map(({ amount, type, unit }) => ({ amount: converter.imperialToMetric[unit](amount), unit: converter.imperialToMetric.labels[unit], type: "metric" })); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.