I have a array with json objects. some objects properties values I need to convert to number from string. I need to push converted number value json to new list. I tried using floatparse but didnt succeed. code
var json = [{
"id" : "0",
"msg" : "hi",
"cost" : "250.24",
"discount": "10"
},
{
"id" : "1",
"msg" : "there",
"cost" : "45.00",
"discount": "0"
}];
var json1 = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
for (const prop in json[key]) {
const parsed = parseFloat(json[key][prop]);
res[key][prop] = isNaN(parsed) ? json[key][prop] : parsed;
// need to push array of modified json object value converted to number from string into json1
}
}
}
CodePudding user response:
I prefer a map solution:
var json = [{
"id": "0",
"msg": "hi",
"cost": "250.24",
"discount": "10"
},
{
"id": "1",
"msg": "there",
"cost": "45.00",
"discount": "0"
}
];
const json1 = json.map(obj =>
Object.fromEntries(Object.entries(obj).map(([key, value]) => {
const parsedValue = parseFloat(value);
return [
key,
isNaN(parsedValue) ? value : parsedValue
];
})));
console.log(json1);
To take it back to loops however:
var json = [{
"id": "0",
"msg": "hi",
"cost": "250.24",
"discount": "10"
},
{
"id": "1",
"msg": "there",
"cost": "45.00",
"discount": "0"
}
];
const json1 = [];
for (const obj of json) {
const mappedObj = {};
for (const [key, value] of Object.entries(obj)) {
const parsedValue = parseFloat(value);
mappedObj[key] = isNaN(parsedValue) ? value : parsedValue;
}
json1.push(mappedObj);
}
console.log(json1);
CodePudding user response:
your loop are wrong.
for (var key in json)
=> when you use loop over an array
it's return item
index not key
json.hasOwnProperty(key)
=> your json is an array
you don't need to use hasOwnProperty
it's for object
I wrote 2 way for you:
*: you can use
for convert string
to number
.
*: if you want loop over item keys you can use way1
, check Object.entries
, Object.keys
, Object.values
methods.
const json = [{
"id" : "0",
"msg" : "hi",
"cost" : "250.24",
"discount": "10"
},
{
"id" : "1",
"msg" : "there",
"cost" : "45.00",
"discount": "0"
}];
//way1
const json1 = json.map((item)=>{
return Object.entries(item).reduce((pre,[key,value])=>{
const parsed = value
pre[key] = isNaN(parsed) ? value : parsed
return pre
},{})
})
console.log('json1',json1)
//way2
const json2 = json.map((item)=>{
return {
"id": item.id,
"msg": item.msg,
"cost": item.cost,
"discount": item.discount,
}
})
console.log('json2',json2)