Can you guys give me some technical explanation why we can access object properties using Bracket Notation, without quotes? Using numeric keys, but the JavaScript does convert every key to string, right?
Example:
const people = {
1 : {
name: 'Ronaldo Fenômeno',
age: 42
},
2 : {
name: 'Ayrton Senna',
age: 58
},
test : {
name: 'John Doe',
age: 123
}
}
console.log(people[1]['name']) // why?
console.log(people['2'].name)
console.log(people['test']['name'])
Related
My question is quiet simple.
I have an object that looks like that:
const person = {
name: 'David',
locations: [
{
country: 'Belgium',
},
{
country: 'France',
},
{
country: 'Ireland',
},
],
};
For example I have "person.locations[0].country" as string, that mix dot-notation and bracket notation.
is there a way to convert to an actual chain of property accessor that returns a value?
Thank you.
I have a problem with code I am supposed to work with. I found a syntax I am not familiar with and I have trouble googling the documentation:
export const Something = class Something {
constructor(someObject = {}) {
this.someObject = {...Something.someObjectDefaultAsStaticMethod,...someThing};
};
// The rest of the class
};
I have problems understanding what the three dots (...) in front of the parameter do. And "dots in parameter javascript" is a bad search term. Can someone help me, maybe tell me what this syntax is actually called or just directly link me to documentation?
That is not ES6 but has only been added in ECMAScript 2018.
It is called "Object Rest/Spread Properties" and is part of the Spread Syntax.
... (three dots in Javascript) is called the Spread Syntax or Spread Operator. This allows an iterable such as an array expression or string to be expanded or an object expression to be expanded wherever placed.
I want to list down the mostly used practical Use Cases of the Spread Syntax (Spread Operator). The following has been explained with examples in this stackoverflow answer.
Combine Arrays (Concatenate Arrays)
Copying Arrays
Calling Functions without Apply
Destructuring Arrays
Function Arguments as Rest Parameters
Using Math Functions
Combining Two Objects
Separate a String into Separate Characters
The [...something] is the spread operator. It in essence allows for an array or string to be expanded. You will see it used often in React, but has many other use cases.
MDN has great documentation on the spread operator:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
You can use "..." in an object. In this example below, "...data" gets 'name: "John", age: 24':
const data= { name: "John", age: 24 };
const newData = {
...data, // Here
sex: "Male"
}
console.log(newData);
This is the result:
{ name: "John", age: 24, sex: "Male" }
This is other example with "...data[key]" to add "id" to each object in an array:
const data = [
{ name: "John", age: 24 },
{ name: "Marry", age: 18 },
{ name: "Tom", age: 15 },
]
const newData = [];
for(const key in data) {
const obj = {
id: Number(key),
...data[key] // Here
}
newData.push(obj);
}
console.log(newData);
This is the result:
[
{ id: 0, name: "John", age: 24 },
{ id: 1, name: 'Marry', age: 18 },
{ id: 2, name: 'Tom', age: 15 }
]
Context: One of the use cases is to do a "copy", but you should take care of this particular "by reference" behavior when working with sub-properties.
Finding: Take care that sub-properties are NOT passed by value, but by reference. In other words, only first level properties are passed as a copy "by value". See the example:
sourcePerson = { name: 'John', colors: ["red", "blue"] }
targetPerson = { ...sourcePerson }
console.log("Target person result:\n", JSON.stringify(targetPerson), "\n\n") //it seems a copy, but...
console.log("Let's update the name source value:\n")
sourcePerson.name = 'Kevin'
console.log("Updated source person:\n", JSON.stringify(sourcePerson), "\n")
console.log("Target person is NOT updated, It keeps a copy by value\n")
console.log(JSON.stringify(targetPerson), "\n\n")
//But if you update a sub-property, it has NOT been copied by value
console.log("Let's update a color sub-property:\n")
sourcePerson.colors[0] = "YELLOW"
console.log("Updated source person:\n", JSON.stringify(sourcePerson), "\n")
console.log("Target person is updated BY REFERENCE!\n")
console.log(JSON.stringify(targetPerson)) // it is not a copy, it is a reference!
console.log("\nCONCLUSION: ... spread syntax make a copy 'by value' for first level properties, but 'by reference' for sub-properties, so take care!\n")
I have a string passed from server which was called with AJAX and I have to convert the string into a nested array which will be used to populate on PDF.
For example:
var tableData = "[{ name: 'Bartek', age: 34 },{ name: 'John', age: 27 },{ name:'Elizabeth', age: 30 }]";
and I need to convert into an array in JavaScript which will be like this:
var newTableData = [
{ name: 'Bartek', age: 34 },
{ name: 'John', age: 27 },
{ name: 'Elizabeth', age: 30 }
];
How can I do that?
As pointed out in the comments, the best solution would be to return a valid JSON from the server and to parse it using JSON.parse.
You can use tools like https://jsonlint.com/ or JSV to check that your JSON is valid.
If because of some "real world problem", your servers aren't JSON complaint, you can use a dirty parser like dirty-json or write your own JSON parse.
dirty-json does not require object keys to be quoted, and can handle single-quoted value strings.
var dJSON = require('dirty-json');
dJSON.parse("{ test: 'this is a test'}").then(function (r) {
console.log(JSON.stringify(r));
});
// output: {"test":"this is a test"}
Your last resort, while technically possible and the easiest to implement, is probably your worst choice because of it's dangers. but it would work out of the box: eval.
eval(tableData);
// [ { name: 'Bartek', age: 34 },
// { name: 'John', age: 27 },
// { name: 'Elizabeth', age: 30 } ]
By slightly changing how you return the string from the server you can JSON.parse it
var dataString = '[{"name":"Bartek","age":34},{"name":"John","age":27},{"name":"Elizabeth","age":30}]';
var data = JSON.parse(dataString);
console.log(data);
Use eval() method The completion value of evaluating the given code. If the completion value is empty, undefined is returned:
var tableData = "[{ name: 'Bartek', age: 34 },{ name: 'John', age: 27 },{ name:'Elizabeth', age: 30 }]";
tableData = eval(tableData);
console.log(tableData[0]);
I have a problem with code I am supposed to work with. I found a syntax I am not familiar with and I have trouble googling the documentation:
export const Something = class Something {
constructor(someObject = {}) {
this.someObject = {...Something.someObjectDefaultAsStaticMethod,...someThing};
};
// The rest of the class
};
I have problems understanding what the three dots (...) in front of the parameter do. And "dots in parameter javascript" is a bad search term. Can someone help me, maybe tell me what this syntax is actually called or just directly link me to documentation?
That is not ES6 but has only been added in ECMAScript 2018.
It is called "Object Rest/Spread Properties" and is part of the Spread Syntax.
... (three dots in Javascript) is called the Spread Syntax or Spread Operator. This allows an iterable such as an array expression or string to be expanded or an object expression to be expanded wherever placed.
I want to list down the mostly used practical Use Cases of the Spread Syntax (Spread Operator). The following has been explained with examples in this stackoverflow answer.
Combine Arrays (Concatenate Arrays)
Copying Arrays
Calling Functions without Apply
Destructuring Arrays
Function Arguments as Rest Parameters
Using Math Functions
Combining Two Objects
Separate a String into Separate Characters
The [...something] is the spread operator. It in essence allows for an array or string to be expanded. You will see it used often in React, but has many other use cases.
MDN has great documentation on the spread operator:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
You can use "..." in an object. In this example below, "...data" gets 'name: "John", age: 24':
const data= { name: "John", age: 24 };
const newData = {
...data, // Here
sex: "Male"
}
console.log(newData);
This is the result:
{ name: "John", age: 24, sex: "Male" }
This is other example with "...data[key]" to add "id" to each object in an array:
const data = [
{ name: "John", age: 24 },
{ name: "Marry", age: 18 },
{ name: "Tom", age: 15 },
]
const newData = [];
for(const key in data) {
const obj = {
id: Number(key),
...data[key] // Here
}
newData.push(obj);
}
console.log(newData);
This is the result:
[
{ id: 0, name: "John", age: 24 },
{ id: 1, name: 'Marry', age: 18 },
{ id: 2, name: 'Tom', age: 15 }
]
Context: One of the use cases is to do a "copy", but you should take care of this particular "by reference" behavior when working with sub-properties.
Finding: Take care that sub-properties are NOT passed by value, but by reference. In other words, only first level properties are passed as a copy "by value". See the example:
sourcePerson = { name: 'John', colors: ["red", "blue"] }
targetPerson = { ...sourcePerson }
console.log("Target person result:\n", JSON.stringify(targetPerson), "\n\n") //it seems a copy, but...
console.log("Let's update the name source value:\n")
sourcePerson.name = 'Kevin'
console.log("Updated source person:\n", JSON.stringify(sourcePerson), "\n")
console.log("Target person is NOT updated, It keeps a copy by value\n")
console.log(JSON.stringify(targetPerson), "\n\n")
//But if you update a sub-property, it has NOT been copied by value
console.log("Let's update a color sub-property:\n")
sourcePerson.colors[0] = "YELLOW"
console.log("Updated source person:\n", JSON.stringify(sourcePerson), "\n")
console.log("Target person is updated BY REFERENCE!\n")
console.log(JSON.stringify(targetPerson)) // it is not a copy, it is a reference!
console.log("\nCONCLUSION: ... spread syntax make a copy 'by value' for first level properties, but 'by reference' for sub-properties, so take care!\n")
I have an array of objects. If I do a console.log, I see this data.
[Object,Object,Object]
0: Object
Name: Ria
Age: 27
Job: Analytics & Review
1: Object
Name: Brian
Age: 23
Job: Admin
2: Object
Name: Rick
Age: 32
Job: Analytics & Review
As you can see at the Job part, I have & symbol. I want to replace that & with & since html does not allow & to pass directly through ajax since its a reserved entity.
Can someone let me know how I can replace & with & wherever they exist.
You can replace it
var data = [{ Name: 'Ria', Age: 27, Job: 'Analytics & Review'},
{ Name: 'Brian', Age: 23, Job: 'Admin'},
{ Name: 'Rick', Age: 32, Job: 'Analytics & Review'}];
data.forEach(function(currentValue, index, array) {
array[index] = JSON.parse(JSON.stringify(array[index]).replace('&', '&'));
});
Idea is to convert your entire array of object into string and then use regex to replace the symbol and then parse back the array of objects back from the string. Try this.
var newArray = JSON.parse(JSON.stringify(array).replace(/&/g,'&'));