how to access the key in json object in react - javascript

I am getting the object below its in json form. i wanted to access only user key from the below object. I tried destructuring the object but didnt got expected value;
const logg=window.localStorage.getItem("userInfo");
const {user}=logg;
console.log(user);
console.log(logg.user);
console.log(logg);
{"success":true,"user":{"avatar":{"public_id":"avatars/laqmzy3nuqa5vl7awprh","url":"https://res.cloudinary.com/randomID/image/upload/v1659523730/avatars/laqmzy3nuqa5vl7awprh.jpg"},"_id":"62ea5294ff799046c8173fef","name":"sumit khatri","email":"ss#sss.com","password":"$2a$10$nSK2JqUSCdVGIVVBzo1IDerU3jrNFfHRDBESV0Ql6y.vWohZiugEG","role":"admin","createdAt":"2022-08-03T10:48:52.355Z","__v":0},"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyZWE1Mjk0ZmY3OTkwNDZjODE3M2ZlZiIsImlhdCI6MTY1OTUyNzM1NCwiZXhwIjoxNjU5OTU5MzU0fQ.TLJYRAm83qQuLVhVkIqYK0u7WetCm9Hn376VvEPX1Ig"}

For the data you actually posted at the bottom of your Q, it would be a simple dereference:
const logg = {"success":true,"user":{"avatar":{"public_id":"avatars/laqmzy3nuqa5vl7awprh","url":"https://res.cloudinary.com/randomID/image/upload/v1659523730/avatars/laqmzy3nuqa5vl7awprh.jpg"},"_id":"62ea5294ff799046c8173fef","name":"sumit khatri","email":"ss#sss.com","password":"$2a$10$nSK2JqUSCdVGIVVBzo1IDerU3jrNFfHRDBESV0Ql6y.vWohZiugEG","role":"admin","createdAt":"2022-08-03T10:48:52.355Z","__v":0},"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyZWE1Mjk0ZmY3OTkwNDZjODE3M2ZlZiIsImlhdCI6MTY1OTUyNzM1NCwiZXhwIjoxNjU5OTU5MzU0fQ.TLJYRAm83qQuLVhVkIqYK0u7WetCm9Hn376VvEPX1Ig"};
const user = logg.user;
console.log(user);
But if it's still in string form like Alaa said, then you need to do:
const logg = '{"success":true,"user":{"avatar":{"public_id":"avatars/laqmzy3nuqa5vl7awprh","url":"https://res.cloudinary.com/randomID/image/upload/v1659523730/avatars/laqmzy3nuqa5vl7awprh.jpg"},"_id":"62ea5294ff799046c8173fef","name":"sumit khatri","email":"ss#sss.com","password":"$2a$10$nSK2JqUSCdVGIVVBzo1IDerU3jrNFfHRDBESV0Ql6y.vWohZiugEG","role":"admin","createdAt":"2022-08-03T10:48:52.355Z","__v":0},"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYyZWE1Mjk0ZmY3OTkwNDZjODE3M2ZlZiIsImlhdCI6MTY1OTUyNzM1NCwiZXhwIjoxNjU5OTU5MzU0fQ.TLJYRAm83qQuLVhVkIqYK0u7WetCm9Hn376VvEPX1Ig"}';
const user = JSON.parse(logg).user;
console.log(user);

The item is in string format try JSON parsing it const {user}=JSON.parse(yourString)

Related

Retrive alle values as array on key in firebase for react native

Hey i have a list of calendar evnets where the key is by date but i would like u get out all values as a array of data
but i wish to get the data out kinda like this but ofc with the rest of the values i have
'2012-05-25': [{date: '2021-04-10', name: "",},{date: '2021-04-10', name: "",}]
is there any way using firebase query to get it out in the format over ?
Something like this should do the trick:
cons ref = firebase.database.ref("calendar/events");
ref.once("value").then((snapshot) => {
let result = {};
snapshot.forEach((daySnapshot) => {
result[daySnapshot.key] = [];
daySnapshot.forEach((eventSnapshot) => {
result[daySnapshot.key].push(eventSnapshot.val());
})
})
console.log(result);
});
So we load all data from the database and then use two nested forEach loops to handle the dynamic levels underneath, and result[daySnapshot.key] to get the date key.

filter fire-base keys with given value

I have a fire base data structured like this:
I want to list all the keys under candidate_employer that start with for example "5_" using JavaScript
Something like this should work:
let root = firebase.database().ref();
let ref = root.child("chat/candidate_employer");
let query = ref.orderByKey().startAt("5_").endAt("5~");
query.once("value").then(function(results) {
results.forEach(function(snapshot) {
console.log(snapshot.key);
})
})
Also see the Firebase documentation on ordering and filtering data.

delete user from json table in js

So I'm a beginner to js and I have a table of users in a json file and I'm making an account delete feature. I have a find set up to find the user and it works fine but I can't figure out how to make it delete the user from the file, any help would be appreciated!
Json:
{
"users": [
{
"name": "ImBattleDash",
"Id": "780748c5d4504446bbba3114ce48f6e9",
"discordId": "471621420162744342",
"dateAdded": 1548295371
}
]
}
JS:
function findJson() {
fs.readFile('./linkedusers.json', 'utf-8', function (err, data) {
if (err) message.channel.send('Invalid Code.')
var arrayOfObjects = JSON.parse(data)
let findEntry = arrayOfObjects.users.find(entry => entry.discordId == myCode)
let linkEmbed = new Discord.RichEmbed()
.setTitle('Account unlinked!')
.setDescription('Link your account by friending "BattleDash Bot" on Fortnite and then input the code you get messaged by typing "!link <code>"!')
.setColor('#a900ff');
message.channel.send({embed: linkEmbed});
})
}
EDIT: Not sure if it's an array or a table I don't know a lot about json
You need to use:
Array#find to find a given user by some given criteria.
Array#indexOf to get the index of the found user in users
Array#splice to drop one element starting from the index given by Array#indexOf:
const input = {
"users": [
{
"name": "ImBattleDash",
"Id": "780748c5d4504446bbba3114ce48f6e9",
"discordId": "471621420162744342",
"dateAdded": 1548295371
}
]
}
const removeUser = (criteria, users) =>
users.splice (users.indexOf (users.find (criteria)), 1)
removeUser (
({ Id, discordId }) =>
Id == '780748c5d4504446bbba3114ce48f6e9'
&& discordId == '471621420162744342',
input.users
)
// Output: 0 <-- User has been removed!
console.log(input.users.length)
About persisting the change, it's just about calling JSON.stringify (input) and then just write the contents to the desired output file. See this other Q&A: Writing files in Node.js
With great help from Cat and Matias I came up with this code that works!
function findJson() {
fs.readFile('./linkedusers.json', 'utf-8', function (err, data) {
if (err) message.channel.send('Invalid Code.')
var arrayOfObjects = JSON.parse(data)
let findEntry = arrayOfObjects.users.find(entry => entry.discordId == myCode)
const input = arrayOfObjects;
const removeUser = (criteria, users) =>
users.splice (users.indexOf (users.find (criteria)), 1)
removeUser (
({ Id, discordId }) =>
Id == findEntry.Id
&& discordId == findEntry.discordId,
input.users
)
console.log('unlinked')
fs.writeFile('./linkedusers.json', JSON.stringify(arrayOfObjects, null, 4), 'utf-8', function(err) {
if (err) throw err
console.log('Done!')
})
let linkEmbed = new Discord.RichEmbed()
.setTitle('Account unlinked!')
.setDescription('Link your account by friending "BattleDash Bot" on Fortnite and then input the code you get messaged by typing "!link <code>"!')
.setColor('#a900ff');
message.channel.send({embed: linkEmbed});
})
}
Here's a quick tutorial for you:
"Users" would be either an array (using []) or a javascript object (using {}), your choice. There won't be any actual tables unless you use a database instead of a JSON file (although if your JSON expression is as simple as your example, you could almost think of it as a table.) -- And actually, a third option would be to use the javascript Map type, which is like a beefed-up object, but I won't address that here.
While using an array would make it a bit easier to retrieve a list of data for all users (because arrays are simpler to iterate through), using an object would make it considerably easier to retrieve data for a single user (since you can directly specify the user you want by its key instead of needing to loop through the whole array until you find the one you want.) I'll show you an example that uses an object.
The individual user in your sample code is an example of a javascript object. JSON lets you convert an object to a string (for storage, I/O, and human readability) and back to an object (so javascript can understand it). You use the JSON.stringify() and JSON.parse() methods, respectively for these conversions. The string has to be JSON-formatted or this won't work, and your example is almost in JSON format.
To comply with JSON formatting, you could structure a Users object as follows. (Of course we're looking at the stringified version because mere humans can't easily read an "actual" javascript object):
"Users": { // Each individual user is a property of your users object
"780748c5d4504446bbba3114ce48f6e9": // The Id is the key in the "key/value pair"
{ // The individual user object itself is the value in the key/value pair
// Id is duplicated inside user for convenience (not necessarily the best way to do it)
"id": "780748c5d4504446bbba3114ce48f6e9",
"name": "ImBattleDash", // Each property of the user is also a key/value pair
"discordId": "471621420162744342", //Commas separate the properties of an object
"dateAdded": "1548295371" // All property values need double quotes for JSON compatibility
}, // Commas separate the properties (ie the individual users) of the users object
"446bbba3114ce48f6e9780748c5d4504": // This string is the second user's key
{ // This object is the second user's value
"id": "446bbba3114ce48f6e9780748c5d4504",
"name": "Wigwam",
"discordId": "162744342471621420",
"dateAdded": "1548295999"
}
}
Once you retrieve the string from storage, you convert it to an object and delete a user as follows. (This is broken down into more steps than necessary for clarity.):
let usersObject = JSON.parse(stringRetrievedFromFile);
let userId = "780748c5d4504446bbba3114ce48f6e9";
let userToModifyOrDelete = usersObject[userId];
delete userToModifyOrDelete;
To change the user's discordId instead, you would do:
let discordId = userToModifyOrDelete.discordId; // Not necessary, just shows how to retrieve value
let newDiscordId = "whateverId";
userToModifyOrDelete.discordId = newDiscordId;
And you'd convert the object back into a string to store in your file with:
JSON.stringify(usersObject);
Hopefully that's almost all you need to know about JSON!

Getting data in console but shows undefined in main output

I'm working on a app with electron using axios to get api data, but when i use to display data it shows undefined in screen and when i output it, it shows the correct value!! Some help would be appreciated!
const electron = require('electron');
const path = require('path');
const BrowserWindow = electron.remote.BrowserWindow;
const axios = require('axios');
const notifyBtn = document.querySelector('.notify-btn');
const price = document.querySelector('.price');
const targetPrice = document.querySelector('.target-price');
function getBTC(){
axios.get('https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD&api_key={api_key}')
.then(function(response) {
let cryptos = response.data;
price.innerHTML = '$'+cryptos;
console.log(response.data);
});
}
getBTC();
setInterval(getBTC, 30000);
I get a output in console:
Object: USD: 3560.263(Current price of bitcoin)
I get output on main screen:
'undefined'
I think its because it an object so how can i display an object?
I may be wrong!!
ThankYou!!
It's not
price.innerHTML = '$'.cryptos;
// but
price.innerHTML = '$' + cryptos.USD;
Add .USD because cryptos is an object. And the value is saved into the key USD
You are accessing the property of a string.
price.innerHTML = '$'.cryptos;
^^^ property
I think you wanted to concat values with a + operator
price.innerHTML = '$' + cryptos;
try using
price.innerHTML = '$'+cryptos.USD;
What are you trying to achieve with '$'.cryptos; ?
If you are trying to concatenate some strings this is not how it works!
try "$"+cryptos
You should use only primitive type variables when composing a string.
If you want to show an object, you could simply use JSON.stringify(cryptos) to obtain the JSON string of the whole object.
Otherwise, you could print any other object property that is a primitive type, like cryptos.USD.

Firebase - Data structure issue for extracting an object from nested structure

Firebase - Data structure issue for extracting an object from nested structure.
I want to find the uid and then check if the key is a jobId.
I've labelled accordingly below.
I'm using typescript and angular2 with firebase.
This is my current attempt that returns "null":
var jobId = "-K5fIAiuHM-4xeEQJiIS";
var uid = "3f61ae7a-99a1-4cbf-9c8e-00b2249956a7";
var userRef = this.refApp.child('key').child(uid);
var query = userRef.child('jobId').child(jobId);
query.on('value', (snap) => {
//This returns null
var response = snap.val();
});
This is my database structure:
Your structure is /applications/$userId/$jobId. Use those keys to get to your data.
JSBin Demo
var jobId = "-K5fIAiuHM-4xeEQJiIS";
var uid = "3f61ae7a-99a1-4cbf-9c8e-00b2249956a7";
var refApp = new Firebase('<my-firebase-app>/applications');
var jobRef = refApp.child(uid).child(jobId);
jobRef.on('value', (snap) => console.log(snap.val()));
Right now you're using "key", which I believe is from my previous demo. That's just for show, not for your actual solution. Keep your data structure in mind when reading the sample code, because it can vary.

Categories

Resources