kgandroid kgandroid - 1 month ago 6
Javascript Question

Detect duplicate key and replace its value within an array in javascript

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?

Answer

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 );

Comments