Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do a Key Value pair in Jquery

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading