0

I have an variable FormData which stores Array[object object] and object has its name and values.

How can I access the name and values in an array?

For example, Array[object] has name="fruit" value="1". I want the value and store it in an input hidden field.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • worth reading up on the full array reference here: http://www.w3schools.com/jsref/jsref_obj_array.asp –  Jan 17 '17 at 15:37

4 Answers4

0

console.log(Array[0].name, Array[0].value);

If you want to check for an specific object, you may iterate over the array and check for an specific property like Array[i].value === 1.

Josué Zatarain
  • 791
  • 6
  • 21
0

Assuming arr to be the array of objects, you would need to iterate over each element of array arr and then get the value of the key "name" and "value" at that index.

var arr = [{"name" : "f1", "value" : "1"},{"name" : "f2", "value" : "2"}];
for(var i=0;i<arr.length;i++){
  console.log(arr[i].name);
  console.log(arr[i].value);
}
Mitesh Pant
  • 524
  • 2
  • 15
0
var arr = [{a:1, b:2}, {c:3, d:4}];
    for (var index in arr) {
        document.getElementById("hiddenfield_id").value = arr[index].name;
        document.getElementById("other_hiddenfield_id").value = arr[index].value;
    }

The For in Loop is best for name-value pairs. Also you have to know how the destination inputs are structured to fill them correctly.

Tito
  • 1
  • 1
  • for-in loops should be used on objects not arrays. http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea – Justin Levine Jan 17 '17 at 16:04
0

If you have an array of objects you can match them and assign them to a variable. Once you have found the match you can "break" from the loop to avoid further searching.

    var arr = [{
      name: "fruit",
      value: "1"
    },{
      name: "something else",
      value: "7"
    }];
    var wantedObjecteOutOfArray;
    for(var i = 0; i < arr.length; i++) {
      if(arr[i].name === "fruit" && arr[i].value === "1") {
        wantedObjectOutOfArray = arr[i];
        break;
      }
    }
    document.getElementById('hidden-input').value = wantedObjectOutOfArray.value;
Justin Levine
  • 265
  • 2
  • 16