Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
67
rated 0 times [  70] [ 3]  / answers: 1 / hits: 12628  / 4 Years ago, mon, april 6, 2020, 12:00:00

I would like to know how to convert object properties string to integer in javascript.
I have a obj, which if has property value is number string convert to number in javascript





var obj={
ob1: {id: 21, width:100,height:100, name: image1},
ob2: {id: 22, width:300,height:200, name: image2}
}


function convertIntObj (obj){
Object.keys(obj).map(function(k) {
if(parseInt(obj[k])===NaN){
return obj[k]
}
else{
return parseInt(obj[k]);
}
});
}

var result = convertIntObj(obj);

console.log(result)





Expected Output:



[
{id: 21, width:100,height:100, name: image1},
{id: 22, width:300,height:200, name: image2}
]

More From » arrays

 Answers
2

This should do the work:





var obj = {
ob1: {
id: 21,
width: 100,
height: 100,
name: image1
},
ob2: {
id: 22,
width: 300,
height: 200,
name: image2
}
}


function convertIntObj(obj) {
const res = {}
for (const key in obj) {
res[key] = {};
for (const prop in obj[key]) {
const parsed = parseInt(obj[key][prop], 10);
res[key][prop] = isNaN(parsed) ? obj[key][prop] : parsed;
}
}
return res;
}

var result = convertIntObj(obj);

console.log('Object result', result)

var arrayResult = Object.values(result);

console.log('Array result', arrayResult)





Click Run code snippet so see the result


[#4252] Friday, April 3, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yvettel

Total Points: 517
Total Questions: 101
Total Answers: 102

Location: Vanuatu
Member since Wed, Oct 14, 2020
4 Years ago
yvettel questions
Tue, Jul 27, 21, 00:00, 3 Years ago
Thu, Aug 13, 20, 00:00, 4 Years ago
Wed, Apr 15, 20, 00:00, 4 Years ago
Wed, Apr 1, 20, 00:00, 4 Years ago
;