How to do a Key Value pair in Jquery

Advertisements

I have the following Array X = [1,3,5] and Y = ["X", "Y", "Z"].
I need to generate output that looks like this {1:X}, {3:Y}, {5:Z}

I try this code

var X = [1,3,5];
var Y = ["X", "Y", "Z"];

var myArray = [];
    for (i = 0; i < X.length; i++) {
        myArray.push({ i : Y[i] });
    };

But that code generates a Y array without X array
What jQuery code should I do to make it work?

>Solution :

To generate an output that pairs the elements from arrays X and Y as {X: Y}, you can modify your code as follows:

var X = [1, 3, 5];
var Y = ["X", "Y", "Z"];

var myArray = [];
for (var i = 0; i < X.length; i++) {
    var obj = {};
    obj[X[i]] = Y[i];
    myArray.push(obj);
}

console.log(myArray);

This will produce the desired output:

[{1: "X"}, {3: "Y"}, {5: "Z"}]

In the modified code, we create an empty object obj inside the loop. Then, we assign the value from array Y at index i as the value of the key X[i] in the object obj. Finally, we push the obj object into the myArray array.

Leave a ReplyCancel reply