Yokesh Varadhan
Yokesh Varadhan

Reputation: 1636

Match two Arrays as Object of Array

I have two arrays and I need to make it as object of array

var arr1 = [1,2,3,4,5]
var arr2 = [a,b,c]

Is there any possibility to change the array to this format[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]

Could someone help me?

Upvotes: 1

Views: 88

Answers (4)

Roli Agrawal
Roli Agrawal

Reputation: 2466

I am assuming you need a object like this {"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}

So you can do it like this.

var arr1 = [1,2,3,4,5]
var arr2 = ["a","b","c"];
var result={}
arr2.map(function(k){
result[k]=arr1;
})
console.log(result);

But here I am giving values of keys as arr1 reference so if arr1 will change value of keys in result will also change.

Upvotes: 0

Jry9972
Jry9972

Reputation: 473

Use forEach to iterate through List and get your desired result.

var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];

var result = {} // Result: Object of Array

arr2.forEach(function(val, index) {
    result[val] = arr1;
})

I hope this is easy to understand :)

Upvotes: 0

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19070

Try this code:

var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];

var result = arr2.reduce(function(obj, item) {
  obj[item] = arr1.slice(); // or = arr1 to keep the reference
  return obj;
}, {});

console.log(result); // {"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}

You have 2 cases:

  • To create clones of the array use result[item] = arr1.slice();
  • To keep the reference to the same array use result[item] = arr1;

Check more about the reduce() method.

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

Is there any possibility to change the array to this formate[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]

This is neither an array format nor a valid JSON literal, so this format could only be a string.

Assuming that you are looking for a string in the format you have specified

var output = "[" + arr2.map(function(value){return value+",{" + arr1.join(",") + "}"}).join("],[") + "]";

Upvotes: 0

Related Questions