kgandroid kgandroid - 28 days ago 7
Javascript Question

Cannot get key and value from an array in javascript

I have created an array in the following format:

[ { Label : 1000.0, } , { November Payment : 1000.0, } , { Late fee : 50.0, } , { Additional Principle : 1000.0, } , ]


Now I want to fetch the key i.e Label,November Payment etc in a separate array or in a variable(for a specific index) and their values in another array.

Code I have tried:

var keys = [];
for (var key in ARY) {
if (ARY.hasOwnProperty(key)) {
kony.print("key--->"+key);
kony.print("value--->"+ARY[key]);
keys.push(key);
}
}
alert(keys);
}


But what I get is:

11-04 07:30:34.966: D/StandardLib(1874): key--->0
11-04 07:30:34.966: D/StandardLib(1874): value--->[object Object]
11-04 07:30:34.986: D/StandardLib(1874): key--->1
11-04 07:30:35.016: D/StandardLib(1874): value--->[object Object]
11-04 07:30:35.016: D/StandardLib(1874): key--->2
11-04 07:30:35.025: D/StandardLib(1874): value--->[object Object]
11-04 07:30:35.037: D/StandardLib(1874): key--->3
11-04 07:30:35.037: D/StandardLib(1874): value--->[object Object]
11-04 07:30:35.045: D/WindowsLib(1874): Calling Create createAlert - { alertType : 0.0, message : [ 0, 1, 2, 3, ] , }


As you can see I get key as 0,1,2...

But why not Label,November Payment etc?

I have no idea what wrong I am doing here.

Answer

You could iterate through the array with Array#forEach and the through the keys (get keys with Object.keys) of the object.

var data = [{ Label: 1000.0 }, { 'November Payment': 1000.0 }, { 'Late fee': 50.0 }, { 'Additional Principle': 1000.0 }];
            
data.forEach(function (a, i) {
    Object.keys(a).forEach(function (k) {
        console.log(i, k, a[k]);
    });
});

// single item
var key = Object.keys(data[0])[0];
//                  index /// \\\ get the first key, of only one key exist
console.log(key, data[0][key]);

Comments