John Cooper
John Cooper

Reputation: 7621

Converting an array into an object

Array: ['Date Taken', 'Weight'],

I have this Array and the way I am iterating it is:

for (vb = 0, len = Array.length; vb < len; vb++) {
     alert(Array[vb]); // would give me the Array Values... 
}

Obj: {DateTaken: 'this.getPicker()', Weight: 'this.getWeight()'}
  1. How can I seperate the keys and the values when I am printing? I want the key and value to be alerted separately
  2. Am I constructing the object right way?
  3. Can a key have multiple values? I mean DateTaken:'value 1, value 2' or something like this.

Upvotes: 0

Views: 97

Answers (2)

cellcortex
cellcortex

Reputation: 3176

Somebody might have added custom keys to the Object prototype so generally it is a good practice to check if all the keys are the actual objects properties. To iterate over an objects keys, you would then:

var myObj = { DateTaken: this.getPicker(), Weight: this.getWeight() };
for (var key in myObj) {
  if (myObj.hasOwnProperty(key)) {
    alert("Key: " + key + ", value: " + myObj[key]);
  }
}

If your values can be arrays you can combine this approach with the one you already found yourself for arrays. I'm using a helper 'output' string here to compose the output.

var myObj = { single: "foo", multiple: ["one", "two", 3] };

for (var key in myObj) {
  if (myObj.hasOwnProperty(key)) {
    var output = "key: " + key + ", value = "; 
    // Check for Array
    if (typeof myObj[key] == "object" && myObj[key].length != undefined) {
      output += "[";
      for (var i = 0, len = myObj[key].length; i < len; ++i) {
        output += myObj[key][i] + ",";
      }
      output += "]";
    } else {
      output += myObj[key];
    } 
    alert(output);
  }
}

Upvotes: 1

pixelfreak
pixelfreak

Reputation: 17834

Okay, that's pseudo-Javascript! :)

Here's the real JS:

var myArray = ['Date Taken', 'Weight'];

for (var i = 0, len = myArray.length; i < len; i++)
{
     alert(myArray[i]); // would totally give you myArray Values! 
}

var myObj = { DateTaken: this.getPicker(), Weight: this.getWeight() };

To iterate both the key and value of myObj, you can do this:

for (var i in myObj)
{
   alert('the key is ' + i + ' and value is ' + myObj[i]);
}

The key in myObj can contain anything, so say if you want multiple strings in DateTaken, then it'll look like this:

var myObj = { DateTaken: ['aloha', 'mahalo', 'etc'], Weight: this.getWeight() };

Upvotes: 1

Related Questions