I'm new to JS. In an application I am extending I have to different kinds of views. I one, I want to see full product names, and in the other only their abbreviations.
I wouldn't like to hard-code them but to write them in a file. What's a good way to accomplish that? I thought about creating an json/xml/text file which would look something like this
'product name 1' : 'abbr1'
'product name 2' : 'abbr2'
[...]
but I need the result to work in both directions, like either passing an abbreviation and getting the full name or the other way round. I can use javascript and jquery.
Edit: I want not to hard-code the data because the products are subject to change, so I wouldn't really like them to be in the source code. I think stuff like this which can frequently change should be stored outside the source code so it can be changed easier.
Put your your products data in a global array:
<script>
function product(name, code) {
this.name = name;
this.code = code;
};
var productArray = [ new product("Apple", "a"), new product("Orange", "o") ];
// user array
for (var i = 0; i < productArray.length; ++i)
if (productArray[i].name == "Apple")
console.log(productArray[i].code);
</script>
You could create the array of products in a JSON file. Something like:
[{name: "Product 1", abbr: "pr1"}, {name: "Product 2", abbr: "pr2}...]
Then you could use jQuery's getJSON method as such:
$.getJSON( "ajax/test.json", function( json ) {
// do something with the json
});
However, that being said. I don't see much benefit from this approach, as the JSON would be hard-coded too.
Edit: Actually I do see a benefit. This at least decouples your data source with the retrieval of data.
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.