Pulling Out Value from Within Two-Levels Deep Object - javascript

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

Related

How to replace the object key name dynamically Angular 8

I want to rename the factORLossTree into savefactORLossTree dynamically inside the function from below payload.
I am getting below data on payload after submitting the form.
{
"cluster":"Europe",
"factory":"Caivano",
"factoryId":"Caivano",
"factORLossTree":[
{
"skuid":"000000000067334539",
"skuDescription":"MAG 55ml Mini PistHazelnut 8MP x6x120 EB",
"levelLosses":[
{
"level1":"Line Scheduling Losses",
"variancePer":100
}
],
"isRowChecked":false
}
],
"submitType":"po"
}
Below is my code .
saveOrUpdateORData() {
const formData = Object.assign({}, this.orLosstreeForm.value);
if (formData.factORLossTree.length === 0) {
this.dialogService.openDialog('Data Not Available');
return false;
}
console.log(formData,"formdata");
return;
}
Expected Output
{
"cluster":"Europe",
"factory":"Caivano",
"factoryId":"Caivano",
"savefactORLossTree":[
{
"skuid":"000000000067334539",
"skuDescription":"MAG 55ml Mini PistHazelnut 8MP x6x120 EB",
"levelLosses":[
{
"level1":"Line Scheduling Losses",
"variancePer":100
}
],
"isRowChecked":false
}
],
"submitType":"po"
}
Can anyone please help me to do this.
Sure thing! Worth mentioning that this issue is purely JS and has nothing to do with your framework (e.g. - Angular)
To the point: let's assume that your payload is stored in a variable called payload
First - check if the property exists. Then - replace it:
const propertyName = 'put the property name here'
const newPropertyName = 'put the new property name here'
if (payload.hasOwnProperty(propertyName)) {
payload[newPropertyName] = payload[propertyName]
delete payload[propertyName]
}
Why this is working? Because we are creating another reference to the original data before deleting the property. At the end we end-up with one reference having the updated name
If (from some reason) you need to clone the data, follow this pattern instead:
if (payload.hasOwnProperty(propertyName)) {
const clone = JSON.parse(JSON.stringify(payload[propertyName]))
payload[newPropertyName] = clone
delete payload[propertyName]
}
I assume that your property always contains an object. If the type of the property is primitive (e.g. - number, string or boolean) you can just skip the cloning phase all together (primitives are copied by their values while only objects are handled by their reference)

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) || {};

How to set value to the property that does not exist by creating new property in Javascript object?

I have Javascript object as follows.
var data = {
USER_LIKES:
{ userId1:
{ publishedContentId: 1492688420796,
publishedContentId1: 'TIMESTAMP',
publishedContentId2: 1492688750874 },
userId2:
{ publishedContentId: 1492688611936,
publishedContentId1: 1492688730807,
publishedContentId2: 'TIMESTAMP' }
}
}
I can add more contents under existing userIds as follows.
data["USER_LIKES"]["userId1"]["publishedContentId3"] = admin.database.ServerValue.TIMESTAMP;
But I want to add contents under userId that does not exist in the object. For example I want to add content under userId3(not exist).
I have tried to do the same thing as follows
data["USER_LIKES"]["userId3"]["publishedContentId3"] = admin.database.ServerValue.TIMESTAMP;
but returns error TypeError: Cannot set property 'publishedContentId1' of undefined.
So how can I achieve this?
Error message is quite verbose, You need to create userId3 property first
data["USER_LIKES"]["userId3"] = data["USER_LIKES"]["userId3"] || {};
data["USER_LIKES"]["userId3"]["publishedContentId3"] = admin.database.ServerValue.TIMESTAMP
OR
data["USER_LIKES"]["userId3"] = {
publishedContentId3 : admin.database.ServerValue.TIMESTAMP
};

Neo4j + nodejs: create node using javascript object literal

can't find whether this has been asked before or not, so bear with me.
I'm just starting to use Neo4j with a nodejs backend and the neo4j-driver driver. I wonder if it's possible to create a node with several properties without enumerating each one in the second argument to the session.run method.
app.post("/signup", function(req, res) {
var user = req.body; //{userId: "johnsmith", email: "john#smith.com", ...}
session.run("CREATE (u:User {u}) RETURN u", user).then(function(response) {
/*do stuff with newly created user*/
}, function() {
//handle error
});
});
Currently, this yields the following error: {code: 'Neo.ClientError.Statement.ParameterMissing', message: 'Expected a parameter named u' }, and if I change the above to:
app.post("/signup", function(req, res) {
var user = req.body; //{userId: "johnsmith", email: "john#smith.com", ...}
session.run("CREATE (u:User {u}) RETURN u", {u: user}).then(function(response) {
/*do stuff with newly created user*/
}, function() {
//handle error
});
});
then the error reads: { code: 'Neo.ClientError.Statement.TypeError', message: 'Property values can only be of primitive types or arrays thereof' }.
This doesn't make much sense to me, given that the refcard clearly states you can create a node using a map, like so: CREATE (n {map}); so I must obviously be getting something wrong. I hope I don't have to enumerate all a user's properties like so:
session.run("CREATE (u:User {userId: {u.userId}, email: {u.email}, ...}) RETURN u", {u: user}).then(/*...*/)
Thanks in advance
Map could not be the value of the properties
You can set properties using a parameter - http://neo4j.com/docs/developer-manual/current/cypher/clauses/set/#set-set-all-properties-using-a-parameter
So you need to check the input parameter and transform its properties if necessary.
For example:
app.post("/signup", function(req, res) {
var params = {};
//{userId: "johnsmith", email: "john#smith.com", ...}
Object.keys(req.body).forEach( function(k) {
var value = req.body[k];
if (!isPrimitive(val)) value = JSON.stringify(value);
params[k] = value;
});
session.run("CREATE (u:User) SET u = {user} RETURN u", {user: params})
.then(function(response) {
// do stuff with newly created user
}, function() {
// handle error
});
});
Where isPrimitive an abstract function that checks whether a variable is a primitive.
Neo4j only supports storing specific kinds of data structures to a property. To quote from the Cypher Refcard:
Neo4j properties can be strings, numbers, booleans or arrays thereof.
And, to be more exact, in order for an array (or "collection") to be stored as a property value, all its elements must be of the same primitive type.
The answer from #stdob-- provides one possible simple workaround to this (but it stringifies all arrays, even ones that can be stored without conversion).
NOTE: The refacrd needs to be a bit more clear. Nested maps are supported, in general. For instance, you can freely pass in JSON data as Cypher query parameters. However, maps containing nested maps are NOT supported for storing as property values.

Problems reading MongoDb collection with Node.js

I have problems reading this collection with mongoose and Node.js:
I have one JSON inside my Collection and i try to read this with this code:
materias.find().exec(function(err1,materias){
if(err1){console.log(err1); return next();}
for(x=0;x<materias.length;x++){
//console.log(materias[x].Nombre);
//var arreglo=materias[x].Horario[0].Dia; // TRY ONE
var arreglo=JSON.parse(materias[x].Horario[0]); // TRY TWO
console.log(arreglo[0]);
}
//RESPONSE TRY ONE
console.log(arreglo) UNDEFINED
//RESPONSE TRY TWO
undefined [
//if I use JSON.stringify the response is {[object][object]...
enter code here
You don't need to parse JSON manually with mongoose.
You get undefined because you define variable arreglo inside the loop but try to access it outside of it. This should work:
materias.find().exec(function(err1,materias){
if(err1){console.log(err1); return next();}
for(x=0;x<materias.length;x++) {
var arreglo = materias[x].Horario[0]; // TRY TWO
console.log(arreglo);
}
What i suppose the error is: you have database named as materias and you are using the same name for the returned collection. Try changing the return name collection to something other.
materias.find().exec(function(err1,change_name_here){
//required code
}
FINALYYYYYYYYYY i fixed it changing my mongoose model
I had this:
var materias=new Schema({
Nombre:{type:String, required:true},
Docente:{type:String, required:true},
Horario:{type:String, required:true}
});
module.exports = materias;
and change for this:
Horario:[{Dia:String, Hora:String, Tiempo:String}]
for reading:
for(x=0;x<materias.length;x++){
var arreglo=materias[x].Horario; // TRY TWO
console.log(arreglo[0].Dia);
}

Categories

Resources