Skip to content Skip to sidebar Skip to footer

How To Declare An Array In JS (like I'd Do It In PHP)?

Hey, Im trying to make a nested array in JS var lines = new Array( '0'= new Array( 0['time']='10:00:00',

Solution 1:

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 ];

Solution 2:

try this

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

Solution 3:

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);

Solution 4:

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.


Solution 5:

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

Post a Comment for "How To Declare An Array In JS (like I'd Do It In PHP)?"