How can i ignore the javascript convert leading zero to octal?

Viewed 183

I want to convert number to string, buti have a problem about javascript convert number that have leading zero to octal.

I have a list of object like this

const ids = [
  { _id : 1236 },
  { _id : "abc123" },
  { _id : 012019 },
  { _id : 000010 },
  { _id : 001230 }
  { _id : 00000000000000 }
]

and i want to convert all of id in object to string like this

[
  { _id : "1236" },
  { _id : "abc123" },
  { _id : "012345" },
  { _id : "000010 },
  { _id : "001230" },
  { _id : "00000000000000" }
]

So, i write a function like this

updateIds = () => ids.map(i => {
  i._id = i._id.toString()
  return i
})

updateIds()

But the result of this function is ..

[
  { _id: '1236' },
  { _id: 'abc123' },
  { _id: '012019' },
  { _id: '8' },
  { _id: '664' },
  { _id: '0' }
]

how can i ignore javascript convert 000010 and 001230 to octal ?

Ps. I think i cant use pad function to write leading zero because value of _id is dynamic. i don't know that length.

2 Answers

You have to define the base you want to use in the toString call.

If you want the ids to be parsed as base 10, then called toString(10). It's impossible to do the padding to preserve the length because numbers are numbers, so leading zeros are ignored. You can pad to a fixed length, for all the ids:

updateIds = () => ids.map(i => {
  i._id = i._id.toString(10).padStart(9, '0');
  return i
})

Use Constructor call Number("001230"). It will convert all numbers to base 10 only, so you won't have the octal conversion problem

const ids = [
  { _id : 1236 },
  { _id : "abc123" },
  { _id : 012019 },
  { _id : 000010 },
  { _id : 001230 },
  { _id : 00000000000000 }
];

let ans = [];

ids.forEach((val)=>{

    let obj = {};
    obj._id = Number(val["_id"]);
    ans.push(obj);

})

console.log(ans);
Related