简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM