This question already has answers here:
Object property name as number
(6 answers)
Closed 3 years ago.
I am working on an API which consists of nested objects with numeric keys. Here is the data:
{ "data": {"0":{"name":"kp"},"1":{"name":"josan"}}
I am wondering how can a key be numeric. As per my knowledge it should not possible.
axios.get(``)
.then( res => {const persons = res.data;
this.setState({persons});
render(){return ({this.state.persons.data."1".name})
I want to access name of 1.
Use bracket notation like so:
this.state.persons.data["1"].name
You can't use numbers usually because all JavaScript object keys are strings - and it gives you a syntax error if you try to use a number in dot notation:
const obj = { 1: "foo" };
console.log(obj..1);
However, because of a quirk of implicit conversion, numbers in bracket notation works fine:
const obj = { 1: "foo" };
console.log(obj[1]);
You can use [] (bracket) notation
var a={ "data": {"0":{"name":"kp"},"1":{"name":"josan"}}}
console.log(a.data[0].name)
console.log(a.data[1].name)
If { "data": {"0":{"name":"kp"},"1":{"name":"josan"}} is the response from the API, and you are already doing this: const persons = res.data;
Then to get the name you need to use this.state.persons['1'].name.
Related
This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 3 years ago.
Let's say we need to add a property to an existing js object
var billingData = {}
In my case, I want to store input value in the js object
Here's the basic input
<input type="text" class="form-control" id="billingFullName">
We, basically, have two ways to add the property to the js object:
The first one:
billingData["billingFullName"] = document.getElementById('billingFullName').value
And the second one:
billingData.billingFullName = document.getElementById('billingFullName').value
What's the difference between them?
I'm asking, because when I was submitting the js object using AJAX to MVC Controller, where properties where added using the [] notation, the model in the Controller appeared to be null. Whereas, the dot notation appeared to solve the issue and I'm wondering why..
Typically you use bracket notation when you need to define a property dynamically such as with a variable or if the key is not in proper format for dot notation:
const obj = {}
const someKey = 'key'
obj[someKey] = 'somevalue'
console.log(obj.key) // 'somevalue'
console.log(obj.someKey) // undefined
Dot notation is when you already know the key:
const obj = {}
object.key = 'someValue'
This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 3 years ago.
I cannot understand the following code, var formData = {}; I guess defines a object "formData", but why to save each element in the formdata["fullName"]? What is this with []? Isn't it used for array? i confused. Could somebody explain this code? Thank you!
function readFormData(){
var formData = {};
formdata["fullName"] = document.getElementById("fullName").value;
formdata["empID"] = document.getElementById("empID").value;
formdata["salary"] = document.getElementById("salary").value;
formdata["city"] = document.getElementById("city").value;
return formData;
}
In javascript, array keys are defined and referenced with square brackets. Object properties can be defined an accessed the same way or with dot notation.
In your case you do have an object, and it's properties can be accessed using bracket notation.
The following two lines are thus equal:
obj["property"] = value;
obj.property = value;
This question already has answers here:
Why add singe quote to a object's property [duplicate]
(2 answers)
Closed 4 years ago.
In my object literals, I would like to create keys that would not be valid identifiers in order to generate a JSON file like the one in the picture, using JavaScript.
Is it possible to create the object like the following?
var objet = {
targets: [
new Stage(),
{
isStage: false,
name: "Sprite1",
blocks: {
o7d.+f~]6/Bs|=|c/F(=: "Hello"
}
}
]
};
This is what the JSON file looks like:
Yes, you can:
const data = {
blocks: {
"o7d.+f~]6/Bs|=|c/F(=": "Hello"
}
}
console.log(data)
But please be careful what exactly you are doing, because you loose readability with this keys naming.
For understanding purpose, I have picked a sub-set of the object.
You can try following
var blocks = {
"o7d.+f~]6/Bs|=|c/F(=": "Hello" // surround key with quotes
};
console.log(blocks["o7d.+f~]6/Bs|=|c/F(="]); // use bracket notation to fetch
You can use the ES6 feature objet litteral dynamic key:
const illegalKey = 'o7d.+f~]6/Bs|=|c/F(=';
...
blocks: {
[illegalKey]: "Hello"
}
Or just:
blocks: {
'o7d.+f~]6/Bs|=|c/F(=': "Hello"
}
This question already has answers here:
Object property name as number
(6 answers)
Closed 6 years ago.
I have a following JSON representation:
var collectionCopy = JSON.parse(JSON.stringify(
{
1 : {
2: "2"
}
}
));
Why cant I access key "2" using dot notation (i.e. collectionCopy.1.2) ?
You can use the dot notation for accessing an object's properties only on a valid identifiers in the language.
And since numbers (or anything that starts with a number) are not a valid identifiers you can access it (as a property of an object) only with the bracket notation.
This is because the keys are strings not actual numbers:
to access it use:
collectionCopy[1][2]
or
collectionCopy['1']['2']
Relevant docs on accessing properties
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 8 years ago.
I never thought I'd stumble in a problem like that but hey what do you know..
var prop = 'horses'
console.log({
prop: 1
});
How can I have this produce an object with a property horses instead of prop and possibly have it done in a single line? Because I can think of a solution but what I'm really looking for is a one-liner.
You can use bracketed notation:
var obj = {};
obj[prop] = 1;
console.log(obj);
In JavaScript, you can refer to a property either by dot notation and a literal name (foo.bar), or bracketed notation with a string name (foo["bar"]). In the latter case, the string can be the result of any expression, including (in your case) a variable reference.
...but what I'm really looking for is a one-liner.
There's no way to do that as part of an object initializer, though, you have to do it separately. If you want a one-liner, you'll need to do a function call, e.g.:
console.log(makeObj(prop, 1));
where makeObj is
function makeObj(propName, propValue) {
var obj = {};
obj[propName] = propValue;
return obj;
}
Try using JSON to create the object:
console.log(JSON.parse("{\"" + prop + "\":\"1\"}");