JSON/Javascript Object Literal Syntax [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
What is the difference between the following and which is the preferred?
Option 1
var object = {
'propertyName':'propertyValue'
}
Option 2
var object = {
"propertyName":"propertyValue"
}
Option 3
var object = {
propertyName:'propertyValue'
}
I realize option 2 is true JSON syntax.

They're all equivalent in Javascript.
Javascript makes no distinction between using single and double quotes when writing a string.
When specifying the keys of an object literal, you need to quote it if it's not a valid identifier, or if it's a reserved keyword. Otherwise, you can write it as a string, using either quotes.
Preference is a personal style question. Most programs are written using the last syntax, but you can occasionally run into problems. For instance, Internet Explorer rejects class: "value" as a syntax error because class is a reserved word, so it needs to be quoted. I frequently encounter this problem when using jQuery to create elements, e.g.
$("<div>" {
id: "foo",
class: "fooClass"
});
will cause an error in IE.

None of these are JSON. They are all varying versions of JavaScript code which uses JavaScript's literal syntax for object creation. All accomplish the same (depending on the chars or keywords you're using in the property name) and it is up to you which you choose (though you should be consistent).
JSON is a platform independent serialization scheme for transporting data between platforms/environments/processes. Its syntax consists of a subset of JavaScript's literal syntax. JSON is always a string.
In the former, it's your choice. In JSON, the spec is very clear that the style used in your second example would be used when writing JSON (though, again, your second example is not actually JSON). JSON serializing any of those variables would produce the following in a string:
{"propertyName": "propertyValue"}
This is true on any platform which supports JSON.

If the JavaScript code is being run in a browser, there is no difference.
The "preferred" syntax is largely an opinion, but I see property names without quotes more often than not.
Using quotes does allow you to use non alpha numeric characters in property names when defining an object in JSON:
var config = {
"foo.url": "/foo",
"foo.timeout": 3000,
"foo^10": 100
};
config["foo.url"];
I've used this before in a config object where I don't want deeply nested properties, but I do want a sudo namespacing scheme to the property names.

There is no difference between any of these syntaxes. You are free to use any of these if you are using this in javascript.
JSON is a bit different it's cross platform object literal. Programmers mistakenly don't create errorfull code, that's why it's syntax make it strictly use " quotes for keys.
So without quotes
{ "i-name" : "Some value" }
will be totally wrong, as it has hyphen in it.

Related

JSON structure in javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 days ago.
Improve this question
I am trying to create a javascript structure that looks like that:
[{'red': {color:'red},...}]
starting with an array of colors:
const COLORS = ['red','yellow']
This is what I have tried:
const finalArray = COLORS.map(color => ({ [color]: { color } }))
However this produces an array that looks like that:
[{red: {color:'red'}}]
instead of [{'red': {color:'red'}}]
Which is not the same and will prevent the library I am using from understanding the array.
Any idea is welcome.
I edited the question since there where some typos. Hope it’s clearer now.
Thanks
What are the differences between:
[{red: {color:'red'}}]
// and
[{'red': {color:'red'}}]
If it's only a quote related matters, you can do like:
COLORS.map(color => ({ [`'${color}'`]: { color } }));
These are just two ways of representing the same array/object. If you need a string containing the canonical representation of the array/object (with double quotes around the names of the properties), you can use JSON.stringify(finalArray).
Please note this will quote ALL your property names, like in:
[{"red":{"color":"red"}}]
And please note the above is a string, as if you did:
finalString = '[{"red":{"color":"red"}}]'
(Note: this question has been closed, and I agree it's not clear enough. But it's quite evident that the user is confusing the internal structure of an array/object with its external representation, and with the way the array/object is shown by a development environment, browser, etc. As this is a very common problem, mostly in new programmers or newcomers to a tool, the question and the answers may still be helpful.)

How to match a variable with the values inside of an object? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have an object with a few locales inside and I want to check if the variable that returns the current locale, matches some of the locales inside the object.
This is my object:
var LocalesMapping = {
'en_US': 'en-GB',
'es_ES': 'es',
'fr_FR': 'fr',
'hu_HU': 'hu',
'pt_BR': 'pt-BR',
'pt_PT': 'pt-PT'
};
I tried to do it using indexOf(), but it returns -1 when it matchs, instead of the other way around. This is how I did it:
if (Object.values(LocalesMapping).indexOf("'{{ app.request.locale }}'") > -1)
I believe indexOf() is for strings and arrays, not for objects, but I can't really find something useful for objects.
Two things:
"'{{ app.request.locale }}'" looks odd to me. If i assume that the {{...}} part is some template that will get replaced with a value in pre-processing, I'm still left with "'value'" -- note that the value is in literal ' quotes. My guess is that you want to remove the 's in that string literal:
if (Object.values(LocalesMapping).indexOf("{{ app.request.locale }}") > -1)
Also note that you can use includes instead of indexOf:
if (Object.values(LocalesMapping).includes("{{ app.request.locale }}"))
Both of the above will check the values, not the property keys. If you want to check for a matching property key, use hasOwnProperty:
if (LocalesMapping.hasOwnProperty("{{ app.request.locale }}"))
Side note: In ES2015+ environments, you might consider using a Map instead of an object:
const LocalesMapping = new Map([
['en_US', 'en-GB'],
['es_ES', 'es'],
['fr_FR', 'fr'],
['hu_HU', 'hu'],
['pt_BR', 'pt-BR'],
['pt_PT', 'pt-PT'],
]);
Then a check for the key would be:
if (LocalesMapping.has("{{ app.request.locale }}"))
or a check for the value would be:
if ([...LocalesMapping.values()].includes("{{ app.request.locale }}"))

Most efficient/faster way of checking if string belongs to array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to find the most efficient/fastest way of checking if a string belongs in an array in both Java and JavaScript. For example, I want to find if the string "=" belongs in the array {"+", "-", "=", "*", "/", "!"}
A way to do it in Java is(omitting the main method)
String[] symbols = {"+", "-", "=", "*", "/", "!"};
String equalTo = "=";
for(String i: symbols) {
if(equalTo.equals(i)) {
System.out.print(equalTo + " belongs to symbols.");
}
}
I would like to know if there is a single method which does this work for me in either Java and JavaScript.
The reason I am asking this in both languages is that I want to see if it is easier in Java or JavaScript.
Answers for your question in JavaScript: How do I check if an array includes an object in JavaScript?
E.g. If you search for full match you can use:
["=", "+", "-"].indexOf("=") // => 1
The most efficient way to see if a string is in a collection of strings, is when this collection is already hashed. For example, if you have a HashSet<String> in Java, you can just use the .contains(String) method, which runs in O(1).
If your collection is stored as a ArrayList<String> or array, it takes O(n) time to check if a string is in the collection (also with the .contains(String) method).
Turning a list or array into a set takes O(n) time, but takes longer than checking if a single element is in the list.
So, in conclusion:
If you only want to check for one element if it's in the collection, just iterate over the list that you apparently already have, and check if the element is in the list. For an array, in Java simply use Arrays.asList(symbols).contains(equalTo) and in JavaScript use symbols.contains(equalTo)
If you want to check for a lot of elements whether they are in the collection, then it's better to turn the collection into a set first. In Java, do something like
HashSet<String> set = new HashSet<String>();
set.addAll(Arrays.asList(symbols));
after which you can do set.contains(equalTo).
For JavaScript, that's a little more annoying, but the first thing off the top of my head is like this:
var set = Object.create(null);
for (var i in symbols) {
set[i] = true;
}
Then, you can check if checkTo in set.
Sorry for long answer, but you asked for efficiency right?
In Java you can use Arrays.asList(yourArray).contains(yourValue). If you use jQuery you can use $.inArray(yourValue, yourArray).
The "best" way to do it really depends on the number of values to match against and how often you need to do it.
If the list is long, and you do it often, you'd be better served by creating a set/map/associate-array for fast lookup, or sort the list of values and perform a binary search. In Java, that would be Set<String> or Arrays.binarySearch().
However, in your case the list is short, so a sequential search like you're doing is fine.
But in addition to that, your values are all single-character, so there is a solution that just happens to be the exact same solution for both Java and JavaScript: indexOf()
In Java:
if ("+-=*/!".indexOf(value) != -1) {
// found
}
In JavaScript:
if ("+-=*/!".indexOf(value) != -1) {
// found
}
Eerie, huh?

Iterating through all the instances with name having a common string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Is there a way to access all the object instances starting with a common string.
Example: I have instances named button64, button223, button856471, button229846, etc. I have no control over how these instances are named. I want to push all these in an array.
I am not creating these objects, I just have to write a javascript which sits in this HTML page and collects all the object instances starting with the string 'button'.
The purpose is to reach out to a desired object out of these and change the visual element.
Also, the solution has to be compatible with IE8. Any ideas about how should I iterate?
If you can use jQuery, you could write:
var buttonsArray = [];
$("div").each(function() {
var id = $(this).attr("id");
if (id && id.indexOf("button") == 0) {
buttonsArray.push($(this));
}
});
You can use regular expressions to find any expression matching the pattern. Using the match method, every instance of the pattern is returned as an array.
var str = document.getElementById("sample");
var arr = string.match(/button[\d]*/g);
The regular expression on line two will match any result that has "button" and will stop once it encounters a character afterwards that is not a digit.

Local Variable usage reasoning [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have lot enough functions, which look like:
var functionName = function(e) {
//
};
where all the parameters are getting passed in in a single container e. Most times values are simple values (no functions), ex.:
{ parameter1: 1, parameter2: "Name", parameter3:{ subParameter1: "A"}}
But there're times when I pass in functions as in: { p2:function(){...} }
I have two options when it comes to utilising parameter values:
Options 1: get parameter values from the chain, starting from e: e.parameter1, e.parameter3.subParameter1 etc.
Option 2: use cached parameter values:
var parameter1 = e.parameter1;
var subParameter1 = e.parameter3.subParameter1;
The second option improves readability but increases the number of vars and the size of the code base. On another hand it's much drier when using long chains, i.e. e.p1.p2.p3 etc.
What reasoning should I use for choosing between those two options?
**Update 1 - the question sounds quite subjective, let me re-prase it.**
I don't mind using chains all the way, no local vars codebase is smaller, I can always figure out what's what, are the any cases when caching is a must?
A combination, based on depth(e.p1 vs e.p1.sp2.ssp3) and frequency of use. Deeper sub-properties and high usage of any sub-property both benefit from caching.
Nested property look ups can get costly, and caching the value after executing the look up once is valuable if you're going to use it a lot. This is only more efficient if you're accessing a particular property on the chain more than once, and the more you access it, the more you benefit from caching.
If you only have one level deep(e.p1, e.p2, e.p3) and you're only looking up each property value once, don't bother.
If you're accessing e.p1.sp2.ssp3 all throughout your function, cache it for sure.

Categories

Resources