0

I have a JSON array, and I am trying to apply the toLowerCase method to
the element "first". How would I apply this to the list of customer objects, instead of just one Customer?

Single customer works fine:

console.log(String.prototype.toLowerCase.apply(data.Customers.Customer[0]["first"]))
console.log(String.prototype.toLowerCase.apply(data.Customers.Customer[1]["first"]))

returns jim and jim as expected

But when I try to apply to the array of customers (removed [0]):

console.log(String.prototype.toLowerCase.apply(data.Customers.Customer["first"]))

Error:

TypeError: String.prototype.toLowerCase called on null or undefined at toLowerCase ()

My input json:

var data=JSON.parse('{"Customers":{"Customer":[{"first":["JIM"],"last":["BEAM"],"address":["22. JIM. RD."],"age":["24"],"age2":["2.0"],"Phone":["206-555-0144"]},{"first":["c2"],"last":["r2"],"address":["23. R. RD."],"age":["22"],"age2":["2.2"],"Phone":["999-555-0144"]}]}}')

Rilcon42
  • 9,584
  • 18
  • 83
  • 167

1 Answers1

1

Since data.Customers.Customer is an array, you have to iterate over it.

var data=JSON.parse('{"Customers":{"Customer":[{"first":["JIM"],"last":["BEAM"],"address":["22. JIM. RD."],"age":["24"],"age2":["2.0"],"Phone":["206-555-0144"]},{"first":["c2"],"last":["r2"],"address":["23. R. RD."],"age":["22"],"age2":["2.2"],"Phone":["999-555-0144"]}]}}')


data.Customers.Customer.forEach( c =>{
//  console.log(c)
  c.first = String.prototype.toLowerCase.apply(c.first)
})

console.log(data.Customers.Customer[0]["first"])
console.log(data.Customers.Customer[1]["first"])
Félix Paradis
  • 5,165
  • 6
  • 40
  • 49
  • I was under the impression that apply was significantly faster than a foreach. Would it be in this case? – Rilcon42 Apr 10 '19 at 20:59
  • My understanding is that they're 2 completely different things, apply() allows you to use a method on different objects, but has nothing to do with iteration over arrays. You could look at using at simple for loop or some newer ES6 iterators if performance matters. related: https://stackoverflow.com/questions/5349425/whats-the-fastest-way-to-loop-through-an-array-in-javascript – Félix Paradis Apr 10 '19 at 21:16