9

Hey, Im trying to make a nested array in JS

    var lines = new Array(
                    "0"= new Array(
                                0['time']="10:00:00",
                                0['user']="User1",
                                0['content']="Line1",
                                ),
                    "1"= new Array(
                                1['time']="20:00:00",
                                1['user']="User2",
                                1['content']="Line2",
                                ),
                    "2"= new Array(
                                2['time']="30:00:00",
                                2['user']="User3",
                                2['content']="Line3",
                                ),
                    );

Chrome's debugger tells me the ), at the end of the first nested array is an "Unexpected Token"

0

6 Answers 6

35

From your code it looks like you're trying to use PHP-style arrays in JavaScript. JavaScript arrays don't work like PHP arrays. Here's something that's more likely to work:

const lines = [
  { time: '10:00:00',
    user: 'User1',
    content: 'Line1',
  },
  { time: '20:00:00',
    user: 'User2',
    content: 'Line3',
  },
  { time: '30:00:00',
    user: 'User3',
    content: 'Line3',
  },
];

To explain a littler further, in JavaScript you create a new array like this:

const myArray = [ 5, 10, 15 ];

The square brackets ([]) denote the beginning and end of the array and commas (,) separate the elements of the array. Then, to access the elements, we would do something like this:

alert( myArray[0] );

...which would give 5 (the first, or "0th," element in the array).

Now, whereas PHP has the associative array (array('a' => 1, ...)), in JavaScript there's no "associative array"; rather, you use an "object literal," like this:

const myObject = { a: 5, b: 10, c: 15 };

This creates a new object with properties (you can think of them as keys) named a, b, and c. There are two ways to access a property:

alert( myObject['b'] );
alert( myObject.b );

In both cases, 10 (the value we assigned to property b) would be given.

Now back to your exercise. You'll see that here we've created an array ([]) and given it three elements, each of which is an object literal ({}). To access, say, the user property of the first element, we would do this:

alert( lines[0].user ); // => "User1"

Edit: If you want to name the elements of the outer array, it must be changed to an object literal, and can be nested like so:

const lines = {
  one: {
    time: '10:00:00',
    user: 'User1',
    content: 'Line1',
  },
  two: {
    // ...
  },
  // ...
};

I've named the items one, two, etc. for clarity's sake, but you can use any values you please. However, if you intend to use numeric property names—0, 1, 2, etc—as in your example code, you may as well use the other array rather than the object. Unlike PHP, JavaScript does not allow "gaps" in an array—they'll be filled with undefined. For example:

const myArr = [1, 2];
myArr[5] = 3;
alert( myArr ); // => [ 1, 2, undefined, undefined, undefined, 3 ];
Sign up to request clarification or add additional context in comments.

4 Comments

ahh, i thought i might have got my PHP and JS mixed up, what i get for trying to learn both at once. is it possible to name the keys for the parent arrays as well? (just curious)
Yes it is by doing a var line = { "0": { time: "10:00:00", ... }, ... }. It then becomes an object that you can iterate with for (var i in lines)
Diesal11, I've added some clarification to my answer. In regard to Salman's comment, it's tricky iterating over an object's properties like this for two reasons: First, it may have properties other than the ones you intended, especially if you're using external libraries like jQuery; and second, the properties will not be ordered. If you want to iterate over them in a specific order you should use an array--Object is not an ordered data type.
How do I nest 2 (2x3) arrays within 1 array? And how can I later call certain indexes in those nested arrays (not inline). For example. I want array called "tables" that has two arrays within it "numbers" and "letters" and these two arrays are both multi-dimensional. How could I create that then call the element in the 2nd row, 3rd column of :"letters"?
4

try this

var lines = [ {'time': 'the time', 'user': 'the user', 'content': 'the content'}, {'time': 'the time', 'user': 'the user', 'content': 'the content'}];

Comments

1

here is simple example that will solve tell you about array in side array in java script if element is even it replace with string "even" for odd replace with "odd"

 var numbers = [
        [243, 12, 23, 12, 45, 45, 78, 66, 223, 3],
        [34, 2, 1, 553, 23, 4, 66, 23, 4, 55],
        [67, 56, 45, 553, 44, 55, 5, 428, 452, 3],
        [12, 31, 55, 445, 79, 44, 674, 224, 4, 21],
        [4, 2, 3, 52, 13, 51, 44, 1, 67, 5],
        [5, 65, 4, 5, 5, 6, 5, 43, 23, 4424],
        [74, 532, 6, 7, 35, 17, 89, 43, 43, 66],
        [53, 6, 89, 10, 23, 52, 111, 44, 109, 80],
        [67, 6, 53, 537, 2, 168, 16, 2, 1, 8],
        [76, 7, 9, 6, 3, 73, 77, 100, 56, 100]
    ];

    for(i=0; i < numbers.length ; i++ ) 
    {
    for(j=0 ; j < numbers[i].length; j++)
    {
        if(numbers[i][j]%2===0)
        {
            numbers[i][j]="even";
        }
        else
        numbers[i][j]="odd";


    }

    }
    console.log(numbers);

Comments

0

a small, standard, 'eye' fix


var lines = [{
    'time': 'the time',
    'user': 'the user',
    'content': 'the content'
},
{
    'time': 'the time',
    'user': 'the user',
    'content': 'the content'
}];

Comments

0

well,i don't think the problem is with the square brackets because in javaScript arrays can be declared in any of the following ways -

var arr = new Array(element0, element1, ..., elementN);
var arr = Array(element0, element1, ..., elementN);
var arr = [element0, element1, ..., elementN];

For more solid reference visit this MDN link. The problem according to me could be the choice of keys.
P.S. i am a beginner and just learning from here and there.If i got it wrong then please correct me because this SO question has dragged me into confusion.

Comments

0

Simple way to add all nested values

const order = [
    {
        "quantity": 1,
        "id": "3833085c-864b-47d7-b2a8-e37ef60d3691",
        "val": {
            "sellable": true,
            "out_of_stock": false,
            "discount": null,
            "pack_size": "50",
            "productPrice": 29.5,
            "unit_price": 0.59,
            "name": "Butter Chilli",
            "tamil_name": null,
            "id": "3833085c-864b-47d7-b2a8-e37ef60d3691",
            "price": 29.5,
            "wholesale_price": 29.5,
            "stock": 100,
            "cost_price": null,
            "unit_weight": "50g"
        }
    },
    {
        "quantity": 2,
        "id": "75fe08ab-8438-42db-bb26-da77568b1fea",
        "val": {
            "sellable": true,
            "out_of_stock": false,
            "discount": null,
            "pack_size": "15",
            "productPrice": 29.25,
            "unit_price": 1.95,
            "name": "Anchovy (Nethaly) H/O(Small)",
            "id": "75fe08ab-8438-42db-bb26-da77568b1fea",
            "price": 29.25,
            "wholesale_price": 29.25,
            "stock": 100,
            "unit_weight": "700gm"
        }
    }
]

const totalAmount = (order) => {
    return order.map(product => product.val.price * product.quantity ).reduce((a, b) => a + b, 0).toFixed(2)
}

// Total value is 
console.log(totalAmount(order))
88.00

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.