how to transfer string to number in javascript from nested array

const detail = [{"User": {"id": 1, "name":"jack", "address":[{"zip":"333"}]}}];

I want to change zip string to number using javascript used through map it does not work please guide

detail.map((item) => {
 return item.address.map(e => Number(e.zip)
})

>Solution :

Assuming you want to keep your array update immutable, which can be useful for a number of reasons, such as performing a state update in React, reducing the number of side-effects your code has, if you’re writing functional style code, etc., then what you want is a mapping operation (as you’ve mentioned in your question).

When mapping over detail, you’re mapping over the outermost objects. You need to recreate each object (and its inner objects), so that you can then finally update the inner address array property:

const detail = [{"User": {"id": 1, "name":"jack", "address": [{"zip":"333"}]}}];

const res = detail.map(obj => ({
  ...obj,
  User: {
    ...obj.User,
    address: obj.User.address.map(address => ({...address, zip: +address.zip}))
  }
}));
console.log(res);

By using the spread syntax (...) above, we’re able to create a new outer object with ...obj, with an updated User key, that holds a new object with all the existing properties of the user object (due to ...obj.User). This new User object then has an updated address property, which holds the mapped address objects. By creating new objects, we can avoid updating those in the original detail array (thus keeping the original detail array and its objects available as is for reuse if needed).


If you don’t mind updating your original array’s objects (instead of returning a new array with new objects), then using a regular for/.forEach() loop instead of .map() as shown in the comments below your question or as described here might be more suitable and performant. This will directly modify your objects inside of your detail array instead of returning a new array:

const detail = [{"User": {"id": 1, "name":"jack", "address": [{"zip":"333"}]}}];

for(const {User: {address}} of detail)
  for(const addr of address)
    addr.zip = +addr.zip;

console.log(detail);
  

Leave a Reply