简体   繁体   English

使用 Javascript 访问嵌套的 object JSON 数组

[英]Access nested object JSON array with Javascript

Using Logger.log(response.data.phone) , I'm getting this in my log:使用Logger.log(response.data.phone) ,我在我的日志中得到了这个:

[{label=work, primary=true, value=5558675309}, {label=work, value=6108287680, primary=false}, {value=6105516373, label=work, primary=false}]

What I want is to return the two phone numbers as 5558675309, 6108287680 .我想要的是将这两个电话号码返回为5558675309, 6108287680

I've tried Logger.log(response.data.phone.value) and that doesn't work.我试过Logger.log(response.data.phone.value)但这不起作用。 I've tried ...phone['value'] , I've tried ...phone[0].value and this one does return the first phone number 5558675309 .我试过...phone['value'] ,我试过...phone[0].value并且这个确实返回第一个电话号码5558675309 But I would like it to return all of the value values whenever I put in the phone key.但我希望它在我输入phone键时返回所有value So how would I modify the logger?那么我该如何修改记录器呢?

response.data.phone is an array you can try looping through it: response.data.phone是一个数组,您可以尝试遍历它:

Logger.log(response.data.phone.map(phone => phone.value).join(', '));

 const response = {data: {phone: [{label:'work', primary:true, value:5558675309}, {label:'work', value:6108287680, primary:false}, {value:6105516373, label:'work', primary:false}] } } const Logger = { log: console.log}; Logger.log(response.data.phone.map(phone => phone.value).join(', '));

response.data is an array, response.data.phone does not exist. response.data是一个数组, response.data.phone不存在。 What you want is response.data[n].phone for an integer n .你想要的是 integer nresponse.data[n].phone You can do this with a forEach loop.您可以使用forEach循环执行此操作。

response.data.forEach((element) => Logger.log(element.phone.value));

If for whatever reason you need support for older browsers you can use the older function syntax:如果出于某种原因你需要支持旧浏览器,你可以使用旧的 function 语法:

response.data.forEach(function(element){
    Logger.log(element.phone.value)
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM