简体   繁体   中英

Can I build an index to an associative array from a string in JavaScript?

In my JavaScript code I have an associative (two dimension) array ( myObj[x][y] ), that has in every row n elements (I know n for every row - different in every row) where the first value show the amount (n) like

{"amount"=>"n", "key0"=>"value0","key1"=>"value1"..."keyn"=>"valuen"}

In a loop I need to access all these values like

for (i=o; i=n-1;i++){
  current=myObj[row-x].key-y; //code to do something with current
}

How can I build this index .key-y so I can access values? (If I create a string like "myObj[row-x].key-"+ i.toString()}" (where that construct the index as literal) can be done in some way?

JSON ```

"[{\"object_type\":\"villa\",\"object_name\":\"Villa at Maries\",\"object_id\":\"1\",\"mainimg\":\"images\/maries\/IMG1.jpg\",\"object_descreption\":\"BLA BLA BLA.\",\"smallimg0\":\"images\/maries\/img1f.jpg\",\"smallimg1\":\"images\/maries\/img1a.jpg\",\"smallimg2\":\"images\/maries\/img1b.jpg\",\"smallimg3\":\"images\/maries\/img1c.jpg\",\"amencount\":4,\"amenitie0\":\"A\/C\",\"amenitie1\":\"Kitchen\",\"amenitie2\":\"Wi Fi\",\"amenitie3\":\"Parking\"},{\"object_type\":\"villa\",\"object_name\":\"Villa at Agia Marina\",\"object_id\":\"2\",\"mainimg\":\"images\\agiamarina\\img1.jpg\",\"object_descreption\":BLA BLA BLA\",\"smallimg0\":\"images\/agiamarina\/img1.jpg\",\"smallimg1\":\"images\/agiamarina\/img2.jpg\",\"smallimg2\":\"images\/agiamarina\/img3.jpg\",\"smallimg3\":\"images\/agiamarina\/img4.jpg\",\"amencount\":3,\"amenitie0\":\"A\/C\",\"amenitie1\":\"Wi Fi\",\"amenitie2\":\"Parking\"},{\"object_type\":\"villa\",\"object_name\":\"Villa at Argasi\",\"object_id\":\"6\",\"mainimg\" :\"images\/argasi\/img1.jpg\",\"object_descreption\":\"BLA BLA BLA\",\"smallimg0\":\"images\/argasi\/img1.jpg\",\"smallimg1\":\"images\/argasi\/img2.jpg\",\"smallimg2\":\"images\/argasi\/img3.jpg\",\"smallimg3\":\"images\/argasi\/img4.jpg\"}]"```

Thank you all.. got my answer.. so simple and so silly me !!!!!!!!

Sure. Something like this will loop through all your elements:

var rowAmount;
for (row=0; row < myObj.length; row++) {
    rowAmount = myObj[row].amount;
    for (key=0; key < myObj[row].length - 1; key++) {
        currentValue = myObj[row]["key" + key];
        //code to do something with currentValue and rowAmount
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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