kgandroid
kgandroid

Reputation: 5595

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.

Upvotes: 1

Views: 350

Answers (2)

Gaurav joshi
Gaurav joshi

Reputation: 1799

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

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386570

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

Upvotes: 1

Related Questions