1

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

and how to get it for a specific index,say 0?
done working...thanks a lot...I will accept this answer
0
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.