kgandroid kgandroid - 1 year ago 77
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;
break; //Stop this loop, we found it!

kony.print("In else");

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

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

ARY is a global array defined as

What wrong I am doing here?

Answer Source

This should work

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download