user2702205
user2702205

Reputation: 485

push syntax in Javascript for an array within an array

"elements": [
    {
        "values": [
            {
                "value": 70
            }
        ],
        "dot-style": {
            "dot-size": 2,
            "halo-size": 2,
            "type": "solid-dot"
        },
        "on-show": {
            "type": ""
        },
        "font-size": 15,
        "loop": false,
        "type": "line",
        "tip": "#val#%"
    }
]

In the above array example I need to add data to values array which is part of elements array dynamically. How do I do it using JavaScript push method?

Upvotes: 1

Views: 85

Answers (4)

Mark Walters
Mark Walters

Reputation: 12390

Presuming elements is part of an object called myObj for the example below, you could use either syntax.

myObj["elements"][0]["values"].push({ value: "my new value" });

or

myObj.elements[0].values.push({ value: "my new value" });

Upvotes: 1

mayorbyrne
mayorbyrne

Reputation: 507

if the above is named var obj,

obj['elements'][0]['values'].push(someValue);

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237845

As you will see, it's much easier to conceptualise your code if it is formatted well. Tools like jsBeautifier can help with this task.

First, it's clear that elements is part of a JS object. We'll call it foo, but you'll have to change this to the correct name in your code.

foo.elements[0].values.push({
    value: 'some value'
});

This will add a new object to the values array.

Upvotes: 4

SheetJS
SheetJS

Reputation: 22905

elements[0].values.push({"value": new_value});

Upvotes: 3

Related Questions