understanding Javascript objects syntax [duplicate] - javascript

This question already has answers here:
Javascript object Vs JSON
(5 answers)
Closed 8 years ago.
<!DOCTYPE html>
<html>
<body>
<p>Creating a JavaScript Object.</p>
<p id="demo"></p>
<script>
var person = {
firstName : "John",
"lastName" : "Doe",
age : 50,
"eyeColor" : "blue"
};
document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName + " is " + person.age + " years old.";
</script>
</body>
</html>
result is ---> John Doe is 50 years old.
here whether the property firstName,"lastName" is enclosed in quotes or not the code still works.but what is the technical difference and in which cases it won't work
for example in JSON the person object's firstName property is invalid json syntax unless the quotes are present.
but javascript allows either syntax to work

Javascript object may have key names enclosed in quotes or without quotes. This feature has more significance when the key name contains a special character like -, white space etc.
Foe example
var person = {
first Name : "John", // Will not work
"last Name" : "Doe", // Will work
age : 50,
"eyeColor" : "blue"
};

Related

why does JSON.stringify() adds extra ' ' around the object [duplicate]

This question already has an answer here:
What does "double quotes" mean in chrome ? (This is weird)
(1 answer)
Closed 3 years ago.
what I understand that JSON format is similar as objects in JavaScript just keys are represented as string , hence:
{name:'John'} \\is JavaScript object
{"name":"John"} \\is Json
however when i try this
`var obj = { name: "John", age: 30, city: "New York" };
var myJSON = JSON.stringify(obj);`
I get '{"name":"John","age":30,"city":"New York"}'
why this extra ' ' warping around the object?
There is no extra ' wrapping the object (not that it is an object, it is a JSON representation of an object).
var obj = { name: "John", age: 30, city: "New York" };
var myJSON = JSON.stringify(obj);
var textNode = document.createTextNode(myJSON);
document.body.appendChild(textNode);
You might be using a debugging tool that is using ' characters to inform you that the value of myJSON is a string (because that's the point of JSON.stringify: It takes a JS variable and makes a JSON text out of it, then it stores that text in a string and makes it available to JS).

How to convert JSON object to a different format [duplicate]

This question already has answers here:
JSON.stringify without quotes on properties?
(16 answers)
Closed 3 years ago.
I have a JSON object like this
{
"name": "Test Name",
"age": 24
}
Is there a way I can convert this to a String in a format like
{
name: "Test Name",
age: 24
}
The JSON will be of varying lengths with different properties.
Right now, I am doing this as shown below. This can get too long and messy for larger and more complex JSON objects. I need to know if there is an easier and cleaner solution for this.
let cypherQueryObject = '{';
cypherQueryObject += ` name: "${user.name}";
if (user.age) { cypherQueryObject += `, age: "${user.age}"` };
cypherQueryObject = '}';
The solution that you are looking for is little different than what someone expect. JavaScript's JSON.stringify() generates JSON string and a valid JSON contains " (double quotes only) around keys.
In your case, you are trying to use the JSON string without " around keys. So here is a little simple process to do that. Here I am assuming that you are going to use this in simple kind of JSON strings where the value part of any key don't have key: kind of things then it will work fine of bigger JSONs too.
If it is not like that then you will need to improve the find & replace utility in more efficient form. Regular expressions are great for this work.
Here I have tried to solve your problem like this.
I have used NODE REPL to execute statements so please ignore undefined returned by default.
>
> let o = {
... "name": "Test Name",
... "age": 24
... }
undefined
>
> s = JSON.stringify(o)
'{"name":"Test Name","age":24}'
>
> s = JSON.stringify(o, undefined, 4)
'{\n "name": "Test Name",\n "age": 24\n}'
>
> console.log(s)
{
"name": "Test Name",
"age": 24
}
undefined
>
> for(k in o) {
... s = s.replace("\"" + k + "\":", k + ':')
... }
'{\n name: "Test Name",\n age: 24\n}'
>
> console.log(s)
{
name: "Test Name",
age: 24
}
undefined
>
you can have a look at this as well.

Why Math.sin`1` works and Math.sin'1' not [duplicate]

This question already has answers here:
Invoking a function without parentheses
(9 answers)
Closed 4 years ago.
If I enter this expression in the browser console (with grave accent):
Math.sin`1`
It will return:
0.8414709848078965
But if I enter this expression (with single quote):
Math.sin'1'
It will throw this error:
SyntaxError: Unexpected number
Why does this error happen?
That's what's called a tagged template literal:
fn`string`
assuming fn is a function, will simply result in fn being called with string as the first argument.
Tagged template literal functions are more useful when you have ${ .. } replacements to make. From the MDN example:
var person = 'Mike';
var age = 28;
function myTag(strings, personExp, ageExp) {
var str0 = strings[0]; // "that "
var str1 = strings[1]; // " is a "
return str0 + personExp + str1 + (
ageExp > 99
? 'centenarian'
: 'youngster'
);
}
console.log(myTag`that ${ person } is a ${ age }`);
tag`template literal` is specifically part of the template literal syntax. It doesn’t work for other string literals.

Need Multi-Line JS Strings [duplicate]

This question already has answers here:
Creating multiline strings in JavaScript
(43 answers)
Closed 4 years ago.
I have searched a lot on how to do this, but none of the solutions have been successful in my case.
I have built a very simple JS form which will generate text ready to copy and paste straight into an email.
My only problem now is getting that text appear exactly as I want it in the email (i.e. multi line).
Does anyone have any suggestions based on my code below?
Not duplicate. I have already read/tried the examples in the other post and none of them work. Hence why I am creating a new question specifically for my code.
function myFunction3() {
var b, text;
b = document.getElementById("type").value;
if (b === "rfi") {
text = "This is an RFI email";
} else {
text = "This is a bank details request email";
}
document.getElementById("demo3").innerHTML = text;
}
The HTML part is below:
<p id="demo3"></p>
var a = "First line.";
var b = "Second line.";
console.log(a + "\n" + b);
var a = "First line.";
var b = "Second line.";
document.getElementById("test").innerHTML = a + "<br/>" + b;
<div id="test"></div>

How to add number like 1+1+1=3 not "1"+"1"+"1" = 111 in javascript [duplicate]

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 5 years ago.
Here is my code:
var health = prompt("Type in health");
var attack = prompt("Type in attack");
var defense = prompt ("Type in defense");
function calculatestats(health,attack,defense){
return health/4 + attack + defense
}
alert (calculatestats(health,attack,defense));
I want to make it output "3" when I type in 4, 1, and 1. The javascript is adding the characters, "1", "1", and "1". I want to add it Mathematically, and make it output 3, not 111.
Thank you.
The prompt() returns a string. You have to do explicit type conversion using + or parseInt:
function calculatestats(health,attack,defense){
return +health/4 + +attack + +defense;
}
Better way:
function calculatestats(health,attack,defense){
return parseInt(health)/4 + parseInt(attack) + parseInt(defense);
}

Categories

Resources