This question already has answers here:
How to declare nested objects in JavaScript?
(2 answers)
Closed 7 years ago.
I would like to create a json object such as this that I can send to the server:
{
"email": "some#gmail.com",
"profile": {
"token": "test"
}
}
I can create the JSON but don't know how to create one that has multiple objects like the one above. This is what I've done so far
(In Console)
> var dataModel = { email: "somemail#gmail.com", token: "sometoken"}
> undefined
> dataModel
> Object {email: "somemail#gmail.com", token: "sometoken"}
The token needs to be inside profile
Most modern browsers have JSON.stringify(yourData) and JSON.parse(jsonData);
Just create your object as a plain JavaScript object:
var object = {
email: "some#gmail.com",
profile: {
token: "test"
}
}
Then convert it to JSON:
var json = JSON.stringify(object);
var dataModel = {
email: "somemail#gmail.com",
profile: {
token: "sometoken"
}
};
var dataModelJSON = JSON.stringify(dataModel);
Supported by main browsers: http://caniuse.com/#search=JSON.stringify
try:
var dataModel = { email: "somemail#gmail.com"};
dataModel.profile = {token : "test"}
Related
This question already has an answer here:
ES6 deep nested object destructuring
(1 answer)
Closed 1 year ago.
I have an Apollo query:
const { error, loading, data: user } = useQuery(resolvers.queries.ReturnUser, {
variables: { userId: parseInt(id) },
});
The data object returned from the query has another object called returnUser. So the actual object is:
data: {
returnUser: {
name: 'Some Name'
}
}
In my JSX I want to output the data:
return (
<div>
{ user ?
<p>Profile {user.returnUser.name}</p> :
<div>User not found</div> }
</div>
);
As you can see I need to access the returnUser object on the user object to get the actual user data. This is not great. Is there any way to destructure the data object from the useQuery so I can assign the nested object to user?
//edit: While this looks like a duplicate question, the answer is different due to the async nature of useQuery. If you don't set a default value you'll get an error.
Got the answer thanks to #Pilchard:
const {error, loading, data: {returnUser: user} = {}} = useQuery(resolvers.queries.ReturnUser, {
variables: {userId: parseInt(id)},
});
You can follow the same nesting while deconstructing the data.
e.g.
const data = {
anotherLevel: {
returnUser: {
name: 'Some Name'
}
}
}
const { anotherLevel: {returnUser: { name }}} = data;
console.log(name); // prints Some Name
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 2 years ago.
I feel like my problem is really easy to solve, but I cannot see it. I have simple thing to do, get myObject from another function and store this in my storage object. For this task I created storageHandler function. Everything works fine, but Object.assign is not reaching my 'ID' that I declared in this function earlier. This is weird because I don't know how to tell my function that 'ID' is variable, not a string. I just expect it to be {1212313: {...}} but instead it gives me {ID: {...}}.
Someone have any idea how to fix it?
let storage = {}
const myObject = {
ID: '1223424525221',
name: 'Thomas',
mail: 'example#example.com'
}
storageHandler = data => {
const {ID} = data;
Object.assign(storage, {ID: data})
console.log(storage)
}
storageHandler(myObject)
That's because in javascript this
a = { b: 1 };
is the same as
a = { "b": 1 };
You should change the Object.assign() for something like this
storage[ID] = data;
You should use the value of ID as key of object using [].
Object.assign(storage, {[ID]: data})
You are using string as a property name. Use computed property name like [ID] instead of ID. Computed property allows you to have an expression be computed as a property name on an object.
let storage = {};
const myObject = {
ID: '1223424525221',
name: 'Thomas',
mail: 'example#example.com',
};
storageHandler = (data) => {
const { ID } = data;
Object.assign(storage, { [ID]: data });
console.log(storage);
};
storageHandler(myObject);
This question already has answers here:
Accessing a JavaScript's object property without knowing that property name
(3 answers)
How to access the first property of a Javascript object?
(23 answers)
Getting the first index of an object
(14 answers)
Closed 3 years ago.
I'm calling an API in my application and need to drill down the JSON response. Within it there is a random string that changes so I can't hardcode the value. Is there a way I can access dataset1 no matter what the random string is?
{
"data": {
"Random String that Changes": {
"dataset1": {
"date": {...}
},
"dataset2":{
"date": {...}
}
}
},
"something else": {
...
},
"something else": {
...
}
}
Previously I was hard coding the drill down like such:
this.props.data.randomData['Random String that Changes'].dataset1.date
Also tried:
this.props.data.randomData[0].dataset1.date
You can get all the keys of the object using
const keys = Object.keys(this.props.data);
Now keys is an array of all keys , but if you json always only has 1 key, you can get your data using
this.props.data.randomData[keys[0]].dataset1.date
You can get dataset1
const values = Object.values(this.props.data)
console.log(values[0]['dataset1'])
Make sure that your json includes the "Random String that changes" at first place as shown in your above format.
Reference: Object.values
Try accessing the object like this :
const obj = this.props.data;
obj[Object.keys(obj)[0]].dataset1.date
Reference: How to access the first property of an object in Javascript?
Consider sample data in myObj.
var myObj = {
"data" : {
"Random String that Changes": {
"dataset1": {
"date": "123"
},
"dataset2":{
"date": "123"
}
}
}
}
var randomString =myObj[Object.keys(myObj)[0]];
var dataset1Date =randomString[Object.keys(randomString)[0]].dataset1.date;
console.log(dataset1Date);
So in this way you can access the date which you are trying with
this.props.data.randomData['Random String that Changes'].dataset1.date
Please check the below code for the solution.
var response = {
"data": {
"Random String that Changes": {
"dataset1": {
"date": {...}
},
"dataset2":{
"date": {...}
}
}
},
"something else": {
...
},
"something else": {
...
}
};
var dataInRandomKey = response.data[Object.keys(response.data)[0]];
Now, you have the whole JSON object (in current example, response['data']['Random String that Changes']) in dataInRandomKey variable.
You can try for in loop
var a = {
"data": {
"Random String that Changes": {
"dataset1": {
"date": {...}
},
"dataset2":{
"date": {...}
}
}
},
"something else": {
...
},
"something else": {
...
}
}
var response = a.data;
for(var key in response) {
console.log(response[key].dataset1);
}
This question already has answers here:
Destructuring deep properties
(4 answers)
Closed 4 years ago.
I have this object
const storeObj = {
name: {
firstName: 'abc'
}
}
I can do alias by assigning name to username
const { name: username } = storeObj
I can do nested destructuring like so
const { name: { firstName } } = storeObj
Can I use them both together? I want to achieve one line when aliasing aka renanming and nested destructuring.
Yes, just put those two together - when you want to assign to a different variable name than the property name, put the new variable name after a colon. This works regardless of the level of the nested object.
const storeObj = {
name: {
firstName: 'abc'
}
}
const { name: { firstName: username } } = storeObj;
console.log(username);
This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 6 years ago.
Context: I'm writing a Redux reducer (although this question is not Redux-specific) for my app's settings, which is a nested object. I want to modify the settings object using property names that are given dynamically.
Example:
const settings = {
service: {
username: 'TEST',
password: ''
}
}
// Normally this would be passed by Redux, but for the purposes of this exercise it's hardcoded
const settingKey = 'service.username';
console.log(settings[settingKey]); // undefined
console.log(eval(`settings.${settingKey}`)); // works, but bad
The only way I can think of accessing the subobject without using eval is using a regex to split the settingKey into its component parts:
const match = /(.+)\.(.+)/.exec(settingKey);
console.log(settings[match[1]][match[2]];
const settings = {
service: {
username: 'TEST',
password: ''
}
}
const settingKey = 'service.username';
const match = /(.+)\.(.+)/.exec(settingKey);
console.log(settings[match[1]][match[2]]);
This works, but
It's ugly
It doesn't work for more deeply nested objects
Is there a way of accessing a nested object's properties with a dynamic name without using regexes or eval?
You can do something like this,
var settings = {service: {username: 'TEST', password: ''}}
var key = "service.username";
function getValue(obj, keys){
keys.split(".").forEach(function(itm){
obj = obj[itm];
});
return obj;
}
getValue(settings, key); //"TEST"
Or you can do it simply using Array#reduce,
var settings = {service: {username: 'TEST', password: ''}}
var key = "service.username", result = key.split(".").reduce((a,b) => a[b], settings);
console.log(result); // "TEST"
Another option that doesn't use eval and works with nested properties.
var settings = {service: {username: 'TEST', password: ''}}
var key = "service.username";
console.log(Function('setting', 'return settings.' + key)(settings));
I think you just change one bit:
const settings = {
service: {
username: 'TEST',
password: ''
}
}
console.log(settings['service'].username);