Node.js应用选择嵌套的JSON列

问题描述 投票:0回答:1

我有一个JSON数组,我正在尝试应用toLowerCase方法 元素“第一”。我如何将其应用于客户对象列表,而不仅仅是一个客户?

单个客户工作正常:

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

按预期返回jim和jim

但是当我尝试应用于客户数组时(删除[0]):

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

错误:

TypeError:String.prototype.toLowerCase在null或未定义的toLowerCase()上调用

我的输入json:

var data = JSON.parse('{“Customers”:{“Customer”:[{“first”:[“JIM”],“last”:[“BEAM”],“address”:[“22.JIM。 RD “],” 年龄 “:[” 24 “],” AGE2岁 “:[” 2.0 “],” 电话 “:[” 206-555-0144 “]},{” 第一 “:[” C2" ] ,“last”:[“r2”],“address”:[“23.R。RD。”],“age”:[“22”],“age2”:[“2.2”],“电话”: [ “999-555-0144”]}]}}')

node.js apply
1个回答
1
投票

由于data.Customers.Customer是一个数组,因此必须对其进行迭代。

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"])
© www.soinside.com 2019 - 2024. All rights reserved.