Access data object properties inside an object - javascript

So I have the following piece of code:
const Menus = wp.api.models.Post.extend({
url: wpApiSettings.root + 'fh/v1/menus/' + path,
});
const menus = new Menus();
console.log(menus);
menus outputs the following object:
How would I be able to access the data: { object and it's properties? It looks like it's an object inside an object.
When I do console.log(menus.attribute) that works fine, but console.log(menus.attributes.data) or even console.log(menus.attributes.success) just returns a undefined answer.
I tried doing the following:
console.log(menus.attributes['data'] also with a undefined answer.
All help is appreciated!

Try menus.attributes[0].data.
It may work. If not work, try to console this on chrome browser and share the screenshot

Probably you have an async problem here. You can try console.log the result inside a callback function.
For example you can try a similar approach like this :
import axios from 'axios';
async function getItems() {
const response = await axios.get(SOME_URL);
console.log('done', response);
return response;
}
getItems().then(items => console.log('items: ', items))

If anyone is ever wondering how to access the data, here is how I had this:
const Menus = wp.api.models.Post.extend({
url: wpApiSettings.root + 'fh/v1/menus/' + path,
});
const menus = new Menus();
console.log(menus) outputted an Object with properties that have other objects.
To access those properties inside the object, do the following:
menus.fetch().then(posts => {
const data = posts.data;
}
Now you're able to access your object properties inside the object - I hope this helps.

Related

More Efficient Way to Destructure with Conditional in ReactJs

I have this code in which we retrieve the data or get the data using useQuery. However, it fails anytime I attempt to call it using this method.
const { data: {getSubCategories} } = useQuery(FETCH_SUBCATEGORIES_QUERY);
It appears to throw an error stating that 'getSubCategories' is undefined, so I tried this method:
const { getSubCategories: subCategories } = { ...subCategoryData };
const { getChildCategory } = { ...data };
It works, but I think there is a better approach or more efficient way to destructure something with conditional syntaxes so it can't return undefined I guess I seem to notice it will take a few seconds before it will return data.
Would you mind commenting down below if you don't understand what I am trying to say or need more clarifications. Thank you.
It appears to throw an error stating that 'getSubCategories' is undefined
No, it's throwing an error when data is undefined. You can circumvent that by using a default:
const { data: {getSubCategories} = {} } = useQuery(FETCH_SUBCATEGORIES_QUERY);
If I've understood correctly you can try this: (safely destruct from the object)
const { data: {getSubCategories} } = useQuery(FETCH_SUBCATEGORIES_QUERY) || {};

Firebase: How to reference a path in Firebase using a variable

I'm trying to reference a variable in my Firebase Realtime Database, but my console doesn't display the data that I want. The right uid is logged, however, I don't know how to reference the variable called serial.
componentDidMount() {
const uid = this.state.user.uid;
console.log(uid);
const serial = db.ref(uid + "/serial");
console.log(serial);
Here is the console
Here is my database
Thanks in advance!
If I correctly understand your question you want to get the value of the uid/serial node.
By doing const serial = db.ref(uid + "/serial"); you define a Reference. You need to query the data at this Reference, by using the once() or the on() methods.
For example:
const serialRef = db.ref(uid + "/serial");
serialRef.once('value')
.then(function(dataSnapshot) {
console.log(dataSnapshot.val());
});
Note that the once() method is asynchronous and returns a Promise which resolves with a DataSnapshot.
Can you try this:
componentDidMount() {
const uid = this.state.user.uid;
console.log(uid);
const dbItem = db.ref(uid);
console.log(dbItem.serial);
}

useState append object into an array of object

My object is create an array of object as follows [{},{},{}]
State variable constructor like this:
this.state:{...some states,
parsed:[{}]}
Every object come from get IPFS with async function:
IPFSREADER = element => {
ipfs.cat(convertedIPFSaddress).then(result => {
let cons = result.toString('utf8')
const consdata = JSON.parse(cons);
// NEED useState save consdata to parsed state
}
When I get data, I am pushing this data to state with useState, but I tried as follows way:
this.setState({parsed:consdata}) result: > Object:{some data...}
this.setState({...[parsed],parsed:[consdata]}) result: [0:Object:{some data...}]
When there is a new data coming from ipfs, this only changes data, where is into the array, but doesn't append to tail of previous data.
this.setState(parsed => [...data, parsed]); follow Joseph D.'s answer, but throw ReferenceError: can't access lexical declaration 'data' before initialization error. Try this solution changed above function as follows:
changed the function to async: IPFSREADER = async element => {..
added await in front of ipfs.cat: const { data } = await ipfs.cat(...
How can solve this problem? I tried many solutions, but can't change the result... Thanks.
It looks like you are trying to do setState({...state, parsed: [...state.parsed, consdata]})

Extracting value from an object

I'm working on a discord bot, using discord.js.
I've been working on this command for too long without finding a solution, so I come here to ask for help.
Here is my problem, maybe it's really simple to solve to you, and that would be great :D
I want to create a command that sends a random gif, based on a keyword.
I'm using a node module called giphy-random.
(async () => {
const API_KEY = "hidden";
const gif = await giphyRandom(API_KEY, {
tag: "kawaii"
});
console.log(gif)
}
I would like to be able to get only the value 'url' of the const which is defined by the function (i'm maybe wrong in my words, I'm a beginner) in order to send it in a channel.
You simply want gif.data.url In fact if you change your console.log like this:
console.log(gif.data.url);
You'll see the url printed to the console.
According to the docs, the link is returned in data.url property of the resulting object. So your code should look like:
(async () => {
const API_KEY = "hidden";
const gif = await giphyRandom(API_KEY, {
tag: "kawaii"
});
console.log(gif.data.url)
}
You can simply access field like this:
const API_KEY = "hidden";
const gif = await giphyRandom(API_KEY, {
tag: "kawaii"
});
const {url} = gif.data; // equal to const url = gif.data.url
console.log(gif);
}

Pulling Out Value from Within Two-Levels Deep Object

I am trying to retrieve one particular value from within a two-levels deep object data structure. First off, though, I am saving into a variable within the function, like this:
getTargetId() {
if (this.authenticationService.isAuthenticated()) {
const userInfo = sessionStorage.getItem('currentUser');
console.log(userInfo);
}
}
From:
console.log(userInfo);
I get this back in the console:
{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"...}
What I want to do is specifically pull out the "_id" value here.
I tried:
console.log(userInfo.data._id);
But then my IDE is showing me an error:
'Property '_id' does not exist on type 'string'.
How do I dig out "_id" in this case?
You are accessing it wrong
Try userInfo.data._id
In the log of your object you can see by the {} notation that data is another object, so after accessing data you can access its properties just as you would with any other object.
I also see that you are getting
'Property '_id' does not exist on type 'string'.
This could mean that you never parsed the information. To find out if this is the case this should be right:
Running->
console.log(userInfo);
Returns->
{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"...}
Just after this code:
Running->
console.log(typeof userInfo);
Returns->
"string"
With your edits, I can see that this is the case.
Try:
userInfo = JSON.parse(sessionStorage.getItem('currentUser') );
console.log(userInfo.data._id);
The _id property is under the data key:
const response = {
"token":"sometoken.value",
"data": {
"_id":"8cd0362c0",
"phone":"555-4343"
}
};
console.log(response.data._id)
You can also use destructuring:
const { _id } = response.data;
console.log(_id)
or:
const { data: { _id }} = response;
console.log(_id);
So, as #jonsharpe pointed out, the key was to JSON.parse the string first. So this gets me the value I need for "_id":
getTargetId() {
if (this.authenticationService.isAuthenticated()) {
const userInfo = JSON.parse(sessionStorage.getItem('currentUser'));
console.log(userInfo.data._id);
}
}
Actually your string is returned as JSON string. So you have to parse it into object using JSON.parse() if you are using js or with $.parseJSON() if you are using Jquery. So your updated code now looks like this.
var user ='{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"}}';
var k = JSON.parse(user);
alert(k.data._id);
And Fiddle is here.
Thank You

Categories

Resources