0

I created dropdown and get value from the response, but here is the issue, reverse.config have two value:1 ,2. now I have to print 2, 1 which I am trying to print, I tried using reverse(), but its not working.

jQuery.each(response.config, function (index,value) {
    var select = value.label + '<select class="configurable"  name="' + index + '" >';
    jQuery.each(value.values, function (key, opt) {
        select += '<option value="' + opt.value_index + '">' + opt.label + '</option>>'
    });
    select += '</select>';
    jQuery("#newProduct").append(select);
});
Jay Vaghasiya
  • 1,585
  • 2
  • 6
  • 21
Sagar Parikh
  • 258
  • 2
  • 16

2 Answers2

1

value.values is your object. you can get your keys using Object.keys(value.values) then reverse it now you have keys in reversed order. iterate over it and get you object base on reversed keys array. According to your json asuming below json is same as your format.

var json={
  "41": {
    "values": [
      {
        "valeu_index": 1,
        "label": "op1"
      },
      {
        "valeu_index": 2,
        "label": "op2"
      }
    ],
    "label": "lbl1"
  },
  "91": {
    "values": [
      {
        "valeu_index": 1,
        "label": "opt1"
      },
      {
        "valeu_index": 2,
        "label": "opt2"
      }
    ],
    "label": "lbl2"
  }
}

var values1=[{valeu_index:1,label:"op1"},{valeu_index:2,label:"op2"}]
var values2=[{valeu_index:1,label:"opt1"},{valeu_index:2,label:"opt2"}]
var response={};
response[41]={values:values1,label:'lbl1'};
response[91]={values:values2,label:"lbl2"};
console.log(response);
 var select = '<select class="configurable"  name="config" >';
var reversed=Object.keys(response).reverse(); 

        $.each(reversed, function (key, opt) {
                var obj=response[opt];
                var select = obj.label+'<select class="configurable"  name="config" >';
                debugger;
                $.each(obj.values,function(i,o){
                select += '<option value="' + o.value_index + '">' + o.label + '</option>>'
                });
                 select += '</select>';
            $("#newProduct").append(select);

            });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='newProduct'></div>
Negi Rox
  • 3,364
  • 1
  • 8
  • 15
0

I think you can use reverse on Array

var t = {
  93: { id: 3 },
  141: { id: 2 }
}

jQuery.each(Object.keys(t).reverse(), function( index, value ) {
  console.log(t[value]);
});
Jay Vaghasiya
  • 1,585
  • 2
  • 6
  • 21