0

so i have an array of objects which returns phoneNumber and businessNumber and name. I am trying to extract the businessNumber and phoneNumber and want to slice them from "-" to only show the last 4 digits?

I was able to use the map to extract the businessNumber but how can i split an return them both in the desired format?

myArray = [{
    phoneNumber: "(111) 222-3344",
    businessNumber: "(112) 333-4567",
    name: "Name1"
  },
  {
    phoneNumber: "(111) 222-3344",
    businessNumber: "(112) 333-4567",
    name: "Name1"
  },
  {
    phoneNumber: "(111) 222-3344",
    businessNumber: "(112) 333-4567",
    name: "Name1"
  },
  {
    phoneNumber: "(111) 222-3344",
    businessNumber: "(112) 333-4567",
    name: "Name1"
  },
]

let arr1 = myArray.map(function(obj) {
  return obj.businessNumber.split('-').pop()
})
console.log(arr1)

Thank you in advance.

Somethingwhatever
  • 1,390
  • 4
  • 32
  • 58
  • 1
    Possible duplicate of [Get everything after the dash in a string in javascript](https://stackoverflow.com/questions/573145/get-everything-after-the-dash-in-a-string-in-javascript) – Calvin Nunes Oct 16 '19 at 16:17
  • would you be able to provide an example of the output you want? It's not clear from the question. Thanks – Finnnn Oct 16 '19 at 16:22
  • @Finnnn please check the updated code, i made changes to the return line. but what would be the cleanest way of putting this on business and phone number together at the same time? – Somethingwhatever Oct 16 '19 at 16:25
  • @CalvinNunes Thank you that helped but what would be the cleanest way of putting this on business and phone number together at the same time? – Somethingwhatever Oct 16 '19 at 16:25

2 Answers2

2

you could return both numbers in an array of new objects

let arr1 = myArray.map(function(obj) {
  return {
    businessNumber: obj.businessNumber.split('-').pop(),
    phoneNumber: obj.phoneNumber.split('-').pop() 
  }
})
Finnnn
  • 3,530
  • 6
  • 46
  • 69
1

You could do something like this if you change your map function slightly.

myArray = [{
    phoneNumber: "(111) 222-3344",
    businessNumber: "(112) 333-4567",
    name: "Name1"
  },
  {
    phoneNumber: "(111) 222-3344",
    businessNumber: "(112) 333-4567",
    name: "Name1"
  },
  {
    phoneNumber: "(111) 222-3344",
    businessNumber: "(112) 333-4567",
    name: "Name1"
  },
  {
    phoneNumber: "(111) 222-3344",
    businessNumber: "(112) 333-4567",
    name: "Name1"
  },
]

let updatedArr = myArray.map((obj) => {
  obj.phoneNumber = obj.phoneNumber.split('-').pop()
  obj.businessNumber = obj.businessNumber.split('-').pop()
  return(obj);
})
console.log(updatedArr)
Michael Sorensen
  • 1,850
  • 12
  • 20