I am looking to create following format in array in javascript.
Each item has:
- url -> string (which is login URL)
- name -> string
- inputs -> array
And each input is:
- name -> string
- type -> string
- value -> string
Please guide me , how to do this in JavaScript
-
google for "javascript object array literal"Bergi– Bergi2012年03月19日 11:40:24 +00:00Commented Mar 19, 2012 at 11:40
-
could you clarify your question a bit, by specifying a couple of sample inputs.MrClan– MrClan2012年03月19日 11:42:11 +00:00Commented Mar 19, 2012 at 11:42
3 Answers 3
[
{url: 'http://google.com/',
name: 'google',
inputs: [
{ name: 'search-term', type: 'string', value: 'javascript' },
{ name: 'region', type: 'country-code', value: 'IN' }
]
},
{url: 'http://yahoo.com/',
name: 'yahoo',
inputs: [
{ name: 'search-term', type: 'string', value: 'javascript' },
{ name: 'region', type: 'country-code', value: 'US' }
]
}
]
there you go.
on a related note, JSON might be worth looking at once. Though I must say, the above is not json, only json-like.
2 Comments
code var test = [ {url: 'google.com', name: 'google', inputs: [ { name: 'search-term', type: 'string', value: 'javascript' }, { name: 'region', type: 'country-code', value: 'IN' } ] }, {url: 'yahoo.com', name: 'yahoo', inputs: [ { name: 'search-term', type: 'string', value: 'javascript' }, { name: 'region', type: 'country-code', value: 'US' } ] } ]codeThis would be tricky in a strongly typed language like Java or C#, but it's pretty easy in JavaScript.
Since JavaScript doesn't have strong typing for array values and variables, you can just create an array of object literals. Each object would contain the properties you specified. There's no need to specify the string type on each property--JavaScript will infer that for you.
While this is really easy to do, the drawback is that you're not going to get any type checking, so some code could inadvertently stick an object into one of your string fields and JavaScript won't stop it.
So just beware of the advantages and disadvantages of JavaScript's flexibility, and make sure you're doing server-side sanity checks on your data.
Comments
var items =
[
{
url: "http://...",
name: "FOO",
inputs: [
{
name: "Input1",
type: "LeTypeh"
value: "Levalueh"
},
{
name: "Input2 (Foo)",
type: "LeType2a",
value: "Levalue2j"
}
// ... (insert as many comma separated inputs as you need in the foo item
},
{
url: "http://...",
name: "BAR",
inputs: [
{
name: "Input1",
type: "LeTypeh"
value: "Levalueh"
},
{
name: "Input2 (Bar)",
type: "LeType2a",
value: "Levalue2j"
}
// ... (insert as many comma separated inputs as you need in the bar item here
}
//... (insert as many comma separated items as you need in the array here
]