5

My aim is to get a json array like this one:

var args = [{ name: 'test', value: 1 }, { key: 'test2', value: 2}];

How can I get the below code to build up an array like the above one?

this.dependentProperties = []; //array
function addDependentProperty(depName, depValue) {    
    dependentProperties.push(new Array(depName, depValue));
} 

By using the push method I end up having a json notation like this one:

args:{[["test1",1],["test2",2]]}

4 Answers 4

27
dependentProperties.push({name: depName, value: depValue});
Sign up to request clarification or add additional context in comments.

Comments

8
var args = [{ name: 'test', value: 1 }, { key: 'test2', value: 2}];

...this is an array where each element is a associated-array (=hash, =object).

dependentProperties.push(new Array(depName, depValue));

...you are pushing a (sub-)Array into the parent array. That's not the same as an associative array. You now have a heterogeneous array.

dependentProperties.push({name: depName, value: depValue});

...This is pushing an associated-array into your top-level array. This is what you want. Luca is correct.

Comments

1
newObject = {
 "first": "John",
 "last": "Doe",
 "age": 39,
 "sex": "M",
 "salary": 70000,
 "registered": true,
 "interests": [ "Reading", "Mountain Biking", "Hacking" ]
}

Comments

0
var myarray = [];
var myJSON = "";

for (var i = 0; i < 10; i++) {

    var item = {
        "value": i,
        "label": i
    };

    myarray.push(item);
}

myJSON = JSON.stringify({myarray: myarray});

1 Comment

please learn how-to format code (there's a question mark at the trailing upper corner of the input box :-)

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.