-2

I have 2 arrays namely,

configdata = ["assignee", "shortDesc"];
ticketarray = ["Tom","testDesc"];

I want to store the values as a key value pair in another array, something like this:

ticketData = ["assignee":"Tom","shortDesc":"testDesc"];

Kindly note that the array values are dynamic, so I cannot hardcode them. Is there a way to do so? I am able to achieve the above said requirement but the length always shows 0. This is the code that I am using:

configdata.Incident_Field.forEach(function (k, i) {
   this[k] = ticketarray[i];
}, ticketData);
Prathibha
  • 199
  • 13
Smruti
  • 11
  • 1
  • 1

2 Answers2

1

Other people have explained why your code did not work. I am providing another solution using reduce.

const configdata = ["assignee", "shortDesc"];
const ticketarray = ["Tom", "testDesc"];

let ticketData = configdata.reduce((result, value, index) => {
  result[value] = ticketarray[index];
  return result;
}, {});

console.log(ticketData);

Output:

{
    assignee: "Tom", 
    shortDesc: "testDesc"
}
6324
  • 4,678
  • 8
  • 34
  • 63
0

The below is not a valid structure in JavaScript:

ticketData = ["assignee":"Tom","shortDesc":"testDesc"];

What you need is a JavaScript object. The best you can do is:

  1. Make sure both the array lengths are same.
  2. Associate the key and value by creating a new object.
  3. Use Object.keys(obj).length to determine the length.

Start with the following code:

configdata = ["assignee", "shortDesc"];
ticketarray = ["Tom", "testDesc"];

if (configdata.length == ticketarray.length) {
  var obj = {};
  for (var i = 0; i < configdata.length; i++)
    obj[configdata[i]] = ticketarray[i];
}

console.log("Final Object");
console.log(obj);
console.log("Object's Length: " + Object.keys(obj).length);

The above will give you an object of what you liked, a single variable with all the values:

{
  "assignee": "Tom",
  "shortDesc": "testDesc"
}
Prathibha
  • 199
  • 13