Home > other >  How to store data as an object format in javascript?
How to store data as an object format in javascript?

Time:07-13

I am using PHP framework to develop web application , i am very new to the javascript part i was stuck at one point to store data inside an array as a json object , can you please help me where did i mistaken ..?

<div >
    <label for="exampleInputName1"> Type</label>
        <select name="f_type" id="jobSel"  onchange="myFunction()">
            <option value="">No Selected</option>
            <option value="1">Name</option>
            <option value="2">Gender</option>
        </select>
</div>

<div >
    <label for="exampleInputName1"> Name</label>
    <select name="p_id" id="sel" >
        <option value="">Please select option</option>
    </select>
</div>                              
<script>
function myFunction() {
        const pumpsdata = []
        var e = document.getElementById("jobSel");
        type_value = e.options[e.selectedIndex].value;
        for (var j = 0; j < pumps.length; j  ) {
            if (pumps[j].fuel_type == type_value) {
                pumpsdata[pumps[j].pump_id] = pumps[j].pump_name
            }
        }
        console.log(pumpsdata) // dump shown below 
        var select = document.getElementById('sel');
        //here length is showing zero
        for (var k = 0; k < pumpsdata.length; k  ) { 
            // console.log(pumpsdata[k]);
            select.innerHTML = select.innerHTML   
            '<option value='   pumpsdata[i].id   '>'   pumpsdata[i]['name']   '</option>';
        }
    };
</script>

dump(pumpsdata)

ghaga123: "Joe Root"
​
ghaga565: "Melodie Matthews"

my requirement was i have to store data as like

pumpsdata = [
            {'id' : 'ghaga123','name': 'joe root'},
            {'id' : 'ghaga565' , 'name' : 'Melodie Matthews'}

]

CodePudding user response:

pumpsdata.push({'id':pumps[j].pump_id,'name':pumps[j].pump_name});

CodePudding user response:

method push()

let e = document.getElementById("jobSel");
function myFunction() {
let pumpsdata = []
    pumpsdata.push({
       key: e.targrt.value,
       key: e.targrt.value
})
   } 

myFunction()```
  • Related