0

Working with JS. I have an array of objects. Here is a sample below. You can see that all the values are strings. However, I need to convert the lft and rgt values into integers so that I can compare these values against other values held in a different array. Keeping them as strings and comparing gives me erroneous results.

nodesWithchildren

:Array[1]
0:Object
 category_id:"8"
 created_at:"2016-11-04 14:14:28"
 lft:"17"
 name:"Felt Materials"
 rgt:"22"
 updated_at:"-0001-11-30 0:00:00"
 __proto__:Object

I have searched through Stackoverflow and found various suggestions. All of them use for loops with parseInt which is great BUT they assume that the values either are all string numbers AND they assume that the values are held in a simple array. Not an array of objects.

I tried using this, but this does NOT work. Probably because parseint does not like it. IN fact it crashes the page:

var nodesWithchildrenParsed =[];
 for(var i=0; nodesWithchildren.length;i++){
 nodesWithchildrenParsed[i] = parseInt(nodesWithchildren[i]);}

My first step is converting these values. Once I have the lft and rgt converted to integers I will run another function where I will say something like, "if lft is greater than X and rgt is less than Y then give me the name "felt materials".

Tks !

Vince
  • 1,405
  • 2
  • 20
  • 33

1 Answers1

0

The easy way to convert a string to a number without using parseint() is to simply divide the string by the integer 1. In my case this was a perfect solution as I did not have to deal with the fact that the strings were in an array of objects, other that doing this:

var childNodes=[];
        for(i=0; i < selectedArray.length; i++){
            if((selectedArray[i].lft /1 ) > (nodesWithchildren[0].lft /1) && (selectedArray[i].rgt/ 1) < (nodesWithchildren[0].rgt/1)) {
               childNodes += selectedArray[i].name;
            }
        }

JS will convert the string before undertaking any operations on it. Cody's Example:

console.log( ('2'/1) > ('10'/1) );

Credit goes to Cody and his answer here:

Cody's answer

Community
  • 1
  • 1
Vince
  • 1,405
  • 2
  • 20
  • 33