Skip to content

I can’t access all the elements in an array inside an object

I have array of objects resultArray:

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

My object looks like

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

where n is number of elements inside the diams array.

Assuming

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

"0","3","5" should be index to access the global array diams it looks like

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:

$.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?

Answer

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>