-1

I have array like this:

var data = [[]];
var dataIndex = ['a','b','c'];
var data0 = [1,2,3];
var data1 = [4,5,6];
var data2 = [7,8,9];

I want to make that array to be like this:

data['a'] = [1,2,3];
data['b'] = [4,5,6];
data['c'] = [7,8,9];

I've tried with this code, but it doesn't work.

for(var i=0;i<dataIndex;i++){
   data[data[i]].push('data'+i[i]);
}

I don't know to do that in javascript since I'm new on this. Anyone can help me? thank you.

deus
  • 21
  • 5
  • are you always going to have three arrays of numbers or can the numbers of the given number arrays can be variable? – Risalat Zaman Apr 22 '21 at 06:19
  • @RisalatZaman yes i always using three arrays of number – deus Apr 22 '21 at 06:20
  • @CBroe not yet. i'm going to push array – deus Apr 22 '21 at 06:22
  • Let's take a step back. Where do these variables `data0` .. `data2` come from? Because that's already an inconvenient data structure. The variable name is basically only good to say "that one" and will have changed in your production code to some random single letter; so nothing with `"data" + i` – Thomas Apr 22 '21 at 06:29

3 Answers3

1

By Using function and loop.

var data = {};
var dataIndex = ['a','b','c'];
var data0 = [1,2,3];
var data1 = [4,5,6];
var data2 = [7,8,9];

function covert(){
  const allData = [data0,data1,data2]
  dataIndex.forEach((item,i)=>{
    data[item] = allData[i];
  })
}
covert();
console.log(data)
Toxy
  • 696
  • 5
  • 9
0

Consider using an object(associative array) to save the values

Define your data object as follows

var data = {}

// You can now do the insertion operations as follows

data['a'] = [1,2,3]

// data in your object will be as follows

{'a': [1,2,3]}
iMinion
  • 11
  • 3
0

You can just do it like this then. No need for loops

var data0 = [1,2,3];
var data1 = [4,5,6];
var data2 = [7,8,9];

var data = {
  a : data0,
  b : data1,
  c : data2
};
Risalat Zaman
  • 1,189
  • 1
  • 9
  • 19