简体   繁体   English

我无法访问对象内部数组中的所有元素

[英]I can't access all the elements in an array inside an object

I have array of abjects "resultArray" 我有一个对象数组“ resultArray”

resultArray= Array[object,object,....]

my object looks like 我的对象看起来像

color:"value" ,diams:Array[n]

where n is number of elements inside the diams array. 其中n是diams数组中元素的数量。 assuming 假设

resultArray.diams = "0","3","5"

"0","3","5" should be index to access the global array diams it looks like "0","3","5"应该是索引,以访问看起来像全局数组的直径

var diams = [60,65,68,69,70,75,76,80,81,82,85,90];

I am trying to display all the selected information by user from this object. 我试图显示用户从此对象中选择的所有信息。 This is my code 这是我的代码

$.each(resultArray,function(key,value){
$("#renderedOBJ").append("<p id='p"+key+"'> color: "
+resultArray[key].color+"; Diameter :<span id='s"+key+"'>"
+resultArray[key].diams+"</span> </P>");

I got this 我懂了

color: purple; Diameter :0,2,3

but I wanted 但我想要

color: purple; Diameter :60,68,69 

Thats why I tried to access the global array diams like this 那就是为什么我试图像这样访问全局数组diams

$.each(resultArray,function(key,value){
$("#renderedOBJ").append("<p id='p"+key+"'> Color: "+resultArray[key].color+
"; Diameter: <span id='s"+key+"'>"
+diams[resultArray[key].diams[key]]+"</span> </P>");
  })

But I got only the first value 但是我只有第一个价值

Color: pink; Diameter :60

Could you tell me what am I doing wrong? 你能告诉我我在做什么错吗? Thanks in advanced 提前致谢

You can use map for that: 您可以使用map

resultArray[key].diams.map(i => diams[i])

Or, if you want to stick to jQuery and avoid ES5/6: 或者,如果您想使用jQuery并避免使用ES5 / 6:

$.map(resultArray[key].diams, function(i) {
    return diams[i];
})

 var diams = [60,65,68,69,70,75,76,80,81,82,85,90]; resultArray= [{color:"purple",diams:["0","2","3"]}, {color:"yellow",diams:["0","3","5"]} ]; $.each(resultArray,function(key,value){ $("#renderedOBJ").append("<p id='p"+key+"'> Color: "+resultArray[key].color+ "; Diameter: <span id='s"+key+"'>" +resultArray[key].diams.map(function(a) {return diams[parseInt(a)]}).join(', ')+"</span> </P>"); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div id="renderedOBJ"></div> 

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

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