-1

I am new to javascript.I am trying to build an array with key value pair and I have done that successfully.

This is my current output:

My current Output:

Now what I want is to check the key of each object in the array.If the key already exists then the value for that corresponding key will be updated else a new key with its value will be inserted.

My code:

function pushToAry(name, val) {
//alert("In the array");
var flag=1;
  kony.print("name-->"+name+"  val-->"+val);
   for (var i in ARY) {
    kony.print("ARY[i].name-->"+ARY[i].name+"  ARY[i].val-->"+ARY[i].val);
     if (ARY[i].name == name) {
     kony.print("In if");
        ARY[i].val = val;
        flag=0;
        break; //Stop this loop, we found it!

     }else{
       kony.print("In else");
     }
   }


   if(flag==1){
   kony.print("flag is 1-->"+flag);
   var obj = {};
   obj[name] = val;
   ARY.push(obj);
    }
}

My above code is not working.ARY[i].name and ARY[i].val is coming undefined.

ARY is a global array defined as ARY=[];

What wrong I am doing here?

kgandroid
  • 5,507
  • 5
  • 39
  • 69
  • 1
    Your data structure is a bit odd. You have an array of objects, each with 1 property. It sounds like this is what you actually want to do, but a Javascript Object natively lets you do something very similar: `var foo = {}; foo[name] = val;` – Tibrogargan Nov 04 '16 at 05:21
  • Please look into this post --> http://stackoverflow.com/a/1988361/4361743 – karman Nov 04 '16 at 05:41
  • Downvoter care to explain?? – kgandroid Nov 04 '16 at 05:51

1 Answers1

1

This should work

function pushToAry(name, val) {
        for (var i = 0; i < ARY.length; i++) {
            if (ARY[i].hasOwnProperty(name)) {
                ARY[i][name] = val;
                return;
            }
        }
    
        var obj = {};
        obj[name] = val;
        ARY.push(obj);
    }

    function init() {
        ARY = [];
        pushToAry("Label", 1000.0);
        pushToAry("Label", 1000.1);
        console.log(`ARY has ${ARY.length} entries`);
        console.log(`ARY[0].Label: ${ARY[0].Label}`);
    }

    document.addEventListener( "DOMContentLoaded", init, false );
Tibrogargan
  • 4,508
  • 3
  • 19
  • 38