marky
marky

Reputation: 5068

Better way to build JSON array and retrieve its elements

Here's how I'm initializing and building an array:

var newCountyInfo = new Object();

newCountyInfo.name = newCountyName;
newCountyInfo.state = newCountyState;
newCountyInfo.zips = newCountyZips;
newCountyInfo.branchID = newCountyBranchID;

So I have my four elements in the array. I'm then passing newCountyInfo to another function to pull out the elements for display in some HTML elements.

The only way I know how to get to the individual elements in the function that uses them is this:

JSON.parse(JSON.stringify(newCountyValidation)).name
JSON.parse(JSON.stringify(newCountyValidation)).state
... etc...

There's got to be a better/shorter/more elegant way of doing this!

What is it?

Upvotes: 0

Views: 68

Answers (2)

Matt Ball
Matt Ball

Reputation: 359826

Why are you serializing at all? I don't understand what JSON has to do with this, unless you're using web workers, ajax, or something else which demands serialization. Start with object literal syntax:

var newCountyInfo = {
    name: newCountyName,
    state: newCountyState,
    zips: newCountyZips,
    branchID: newCountyBranchID
};

And just pass the whole object to the other function:

someOtherFunction(newCountyInfo);

Which can access the fields using plain old property accesses:

function someOtherFunction(foo) {
    console.log(foo.name); // whatever was in newCountyname
}

No JSON whatsoever.

Upvotes: 5

Ja͢ck
Ja͢ck

Reputation: 173562

Something like this should work just fine:

var newCountyInfo = {
    name: newCountyName,
    state: newCountyState,
    zips: newCountyZips,
    branchID: newCountyBranchID
}

function test(newCountyValidation)
{
    alert(newCountyValidation.name);
}

test(newCountyInfo);

Upvotes: 1

Related Questions