0

I'm trying to push some datas into my array.

Actually my code looks like this:

arr.push('step1||item1||99');

It works but it's not the best as I need to split it after to manager datas.

How can I transform this into a multidimensional array ?

What I tried:

arr = [];
arr['step'] = 'step1';
arr['name'] = 'item1';
arr['number'] = '99';
arr.push(arr);

But it doesn't work...

Any help please.

4
  • What do you mean by "I need to explode it after to manager datas"? Commented Mar 5, 2016 at 0:37
  • Remember that in JS is split. Commented Mar 5, 2016 at 0:38
  • One major problem with your approach is that arr.push(arr) creates a circular array, where the last element is the entire array. But see my answer below for an alternative approach. Commented Mar 5, 2016 at 0:43
  • 1
    I'd suggest going back and reviewing basic tutorials about JS data types, the difference between objects, and arrays, etc. Perhaps this would help: developer.mozilla.org/en-US/docs/Web/JavaScript/…. Commented Mar 5, 2016 at 2:54

3 Answers 3

3

Is there a reason you don't want these individual data points to be objects?

var arr = [];
var dataPoint = { 'step': 'step1', 'name': 'item1', 'number': 99 };
arr.push(dataPoint);

If this isn't what you're looking for, can you give a fuller explanation of what your dataset should look like so we can better understand the problem?

Sign up to request clarification or add additional context in comments.

1 Comment

var arr = [{ step: 'step1', name: 'item1', number: 99 }];
2

Array holds "indexes"

Object holds "Key" and "Value"

Array example:

var arr = new Array;
arr[0] = 'step1';
arr[1] = 'item1';
arr[2] = '99';
console.log(arr);

Object example:

var obj = new Object;
obj.stop = 'step1';
obj.item = 'item1';
obj.number = 99;
console.log(obj);

Objects in array:

var arr = new Array;
var obj = new Object;
obj.stop = 'step1';
obj.number = 99;

arr.push(obj)
console.log(arr); // Output => [{stop: 'step1', number: 99}]

Comments

0

maybe you mean something like this

arr=[];
var s={
step:'step1',
name:'item1',
number:'99'
}
arr.push(s);
console.log(arr);

s is an object, which works just like an array, but is referenced by a string instead of an integer:

s['step'] === 'step1'
s.step === 'step1'
arr[0] === s

Be aware that there are some differences, like you can't iterate over an object like you can an array: you need to use another method like a "for in" loop, for instance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.