Illep Illep - 3 months ago 5
Node.js Question

Populating a parameter using arrays - Beginner

I am stuck with this issue for a few days now. I am not able to format the values according to the given format.

I have 2 Array objects.

var name = ["sam","Anthony"];
var age = ["4","10"];


The
name
and
age
array may contain more values in it. So it means that the 2 arrays above are dynamic.

I need to extract values from these arrays and add them in the
Item
section as shown in the following code. However, I am not able to hardcode the array content as this array is dynamic in size. It may contain more student records in it. In that case How am I able to construct the following
params
variable after populating the values of the
name
and
age
arrays ?

var params = {
RequestItems: {
"Student": [
{
PutRequest: {
Item: {
"name": "sam",
"age": "4"

}
}
},
{
PutRequest: {
Item: {
"name": "Anthony",
"age": "10"
}
}
}
]
}
};

Answer

Use the map function:

var names = ["sam", "Anthony"];
var age = ["4", "10"];

var params = {
  RequestItems: {
    "Student": names.map(function(c, index) {
      return {
        PutRequest: {
          Item: {
            "name": c,
            "age": age[index]
          }
        }
      };
    })
  }
};
alert(JSON.stringify(params, null, 4));

Comments