Is it possible to have an array of arrays?

Asked

Viewed 75 times

-1

Is it possible to insert into an array, as an element, another array? That is, to make an array of? I arrays.e.:

array[

       [0] => valor => array( 
                             [0]=> valor 1, 
                             [1]=> valor 2,
                             [2]=> valor 3 
                            )

     ];
  • What have you been trying? And the format was not very clear to me George.

  • In javascript you will use objects for multidimensional arrays https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

  • type so in the index of an array one could add another array

  • From what I’ve seen you want something like [tag:JSON] see in this my answer about what JSON is, if you don’t already know it: https://answall.com/a/4171/3082

1 answer

2

Editing

According to the questioner, in reply:

has to look like this format { "1":[ {"name":"John","Age":"21"} ] "2":[ {"name":"Jone","Age":"22"} ] }

Apparently you want to mount a JSON, where each property is a sequential number. What you need then is not an array, but an object.

When converting an array to JSON, you will only have its elements:

JSON.stringify(['fus', 'ro', 'dah']);
// resulta em "["fus", "ro", "dah"]"

In order for each key to be represented verbatim in JSON, you need the following build. Try it on the console:

var objeto = {};
objeto["1"] = { name: "John", age: "21"};
objeto["2"] = { name: "Jone", age: "22"};
JSON.stringify(objeto);

Note that:

  • You have an object that has properties other objects. This is not an array of arrays;
  • That way the keys aren’t necessarily sequential - you can use anything in place of the numbers. Note also that there may be no order guarantee for properties if you run in different browser environments.

Original response

Yes, it is possible. Try the following code in the browser console:

var foo = [];
foo[0] = [1, 2, 3];
foo[1] = [4, 5, 6];
foo;

Note that this is not best practice. If you are going to enter directly into specific indexes, the responsibility is yours to maintain continuous indexes and to ensure that there is no accidental overwriting. This is simple in an example code like the above, but as your code grows it becomes more complicated and open to bugs.

The best way is by using the default array insertion:

var foo = [];
foo.push([1, 2, 3]);
foo.push([4, 5, 6]);
foo;
  • has the format { "1":[ {"name":"John","Age":"21"} ] "2":[ {"name":"Jone","Age":"22"} ] }

  • @George this structure you want is a [tag:JSON] that is different from a simple array, test insert this snippet on the site http://json.parser.online.fr

  • @George edited the answer. What you wanted after all is something other than what you asked.

  • 1

    Here’s a beautiful example: JSON.stringify(['fus', 'ro', 'dah']); only the strong understood

Browser other questions tagged

You are not signed in. Login or sign up in order to post.