0plus1
0plus1

Reputation: 4555

Javascript: multimensional arrays with key value alternative?

Since I'm more versed in php thank in js I'll try to explain what I need from a php perspective. I need to pass to a javascript function an array:

array('fieldname' => 'value', 'fieldname2' => 'value2' ...);

Thne the function would do this

foreach(array as k => v) {
  <input name='fieldname' value='value'/>
  <input name='fieldname2' value='value2'/>
  ...
}

I don't know how to do this, I understand that js don't have multidimensional array, so I wonder what is the correct way to do this in javascript?

p.s. I understand that there is a library that make available the php function to js, but I want to learn what is the best practice to do this in pure js.

Thank you very much

Upvotes: 2

Views: 827

Answers (4)

John Kugelman
John Kugelman

Reputation: 361977

<script type="text/javascript">
// <![CDATA[

  // Create an associative array.
  var array = {'fieldname': 'value', 'fieldname2': 'value2'};

  for (var key in array) {
      // Create an input element and set its name and value.
      var input = document.createElement("input");

      input.name  = key;
      input.value = array[key];

      // There's no simple "insert an element right here"; you have to pick
      // where in the document to add the input box.
      document.body.appendChild(input);
  }

// ]]>
</script>

Upvotes: 5

codez
codez

Reputation: 1391

multidimensianla array in js:

a={a:{a:1,b:2},b:{a:1,b:2}};
a.a.a=5;
a['a']['a']=7;

Upvotes: 0

kasperjj
kasperjj

Reputation: 3664

I might be missing something since I'm not quite sure what you mean when you say multidimensional array... what you are showing in your code is typically called an associative array.

var fields={'fieldname' : 'value', 'fieldname2' : 'value2'};
for(var key in fields){
    var elm=document.createElement('input');
    elm.name=key;
    elm.value=fields[key];
    document.body.appendChild(elm);
}

Upvotes: 0

g.d.d.c
g.d.d.c

Reputation: 48028

In Javascript there are no associative arrays. There are Objects which provide key-value pairings, but they really should not be confused with an associative array. You can do things like this:

var myObject = {
  key1: 'value1',
  key2: 'value2'
};

for (var i in myOjbect) {
  var thisVal = myObject[i];
}

That will allow you to iterate over the properties of the object you've created. Again, while this is similar to what you've requested, it is not exactly the same as an associative array in PHP.

Upvotes: 3

Related Questions