Sen
Sen

Reputation: 773

How to convert object properties string to integer in javascript

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"}
]

Upvotes: 8

Views: 16425

Answers (4)

Nancy Brown
Nancy Brown

Reputation: 418

Hi I would recommend you to use the JSON.stringify() method. It is used to convert object to string which is needed to send data over the web server. It converts the set of variables in the object to a JSON string:

var objToStr = {
  siteName: "W3Docs",
  bookName: "Javascript",
  booksCount: 5
};
var myJSON = JSON.stringify(objToStr);
console.log(myJSON);

Also, you can use the The toString() method. It is also called when you need to convert the object into a string:

var obj = {
  siteName: "W3Docs",
  bookName: "Javascript",
  booksCount: 5
};
function objToString(object) {
  var str = '';
  for (var k in object) {
    if (object.hasOwnProperty(k)) {
      str += k + '::' + object[k] + '\n';

This information is taken from this source.

Upvotes: -2

Boris K
Boris K

Reputation: 1552

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

Upvotes: 10

Mohammad Usman
Mohammad Usman

Reputation: 39322

You can use Object.entries() and .reduce() methods to iterate over the key value pairs in your data and use Number and Number.isNaN() methods to transform the values appropriately.

const data = {
  ob1: {id: "21", width:"100",height:"100", name: "image1"},
  ob2: {id: "22", width:"300",height:"200", name: "image2"}
};

const result = Object.entries(data).reduce((r, [k, o]) => {
    r[k] = Object.entries(o).reduce((r, [k, v]) => {
        let _v = Number(v);
        if(!Number.isNaN(_v)) { v = _v; }
        return (r[k] = v, r);
    }, {});
    return r;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 0

joy08
joy08

Reputation: 9652

Iterating over Object.keys() twice. If the value corresponding to the key is a number then parseInt the value else set the default value which was present earlier

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

var res = {};

Object.keys(obj).forEach(key => {
  res[key] = {};
  Object.keys(obj[key]).forEach(temp => {
    res[key][temp] = !isNaN(obj[key][temp])
      ? parseInt(obj[key][temp], 10)
      : obj[key][temp];
  });
  return res;
});

console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 0

Related Questions