How to parse JSON in node js - javascript

I have this JSON array, and what I want is to get the password field alone
var user = [ { _id: 5902086ecbc0dd11e4870fd9,
password: '$2a$08$FIpkmFT1WDZggQYyBA4CVuop6pelbKBfUEJ1/KAVIV2Si9Ho1EYhi',
email: 'jv100#gmail.com',
lastName: 'v',
firstName: 'j',
updatedDate: 2017-04-27T15:04:14.483Z,
createdDate: 2017-04-27T15:04:14.483Z } ]
I tried to parse it using this code
var obj = JSON.parse(user);
console.log(user.password);
but still it is undefined.

User is already a list of objects, so you don't need to parse it. However, it is an array. So if you meant for it to be an array, you'd need to access the password by using this code:
console.log(user[0].password);

It's already an array there is nothing to parse. You can access your property via :
console.log(user[0].password);
You can't access your property with user.password because user variable is not object, it's an array, your object is stored at the zero index of your array.

You already have JSON object. hence, no need to parse it again.
DEMO
var user = [{ _id: "5902086ecbc0dd11e4870fd9",
password: '$2a$08$FIpkmFT1WDZggQYyBA4CVuop6pelbKBfUEJ1/KAVIV2Si9Ho1EYhi',
email: 'jv100#gmail.com',
lastName: 'v',
firstName: 'j',
updatedDate: "2017-04-27T15:04:14.483Z",
createdDate: "2017-04-27T15:04:14.483Z" } ];
var password = user[0].password;
console.log(password);

The variable 'user' is not a JSON array. It's an array with a single Javascript object as its element.
JSON.parse(arg) can only be used to parse a JSON string to a plain Javascript object. That being said, to access the javascript object within the array, you can do:
var userData = user[0];
To access the password within the variable, userData, you can do:
var password = userData.password;
Log the password to the console with:
console.log(password);

Try This:
var user = [ {_id:'5902086ecbc0dd11e4870fd9',password: '$2a$08$FIpkmFT1WDZggQYyBA4CVuop6pelbKBfUEJ1/KAVIV2Si9Ho1EYhi',email: 'jv100#gmail.com',lastName: 'v',firstName: 'j',updatedDate: '2017-04-27T15:04:14.483Z',createdDate:' 2017-04-27T15:04:14.483Z' } ];
var obj = user[0];
console.log(obj.password);

Related

Store data with a dynamic key in a nested object using local storage

The below object is stored in the localStorage to mimic the server-side login/logout. I have logic in place to find the current user.
let defaultUsers = [
{ email: "test#test.com", password: "test123", favs: [] },
{ email: "dummy#dummy.com", password: "dummy123", favs: [] },
{ email: "example#example.com", password: "example123", favs: [] }
];
The idea is for current user i want to store favorite images [have logic in place to identify the clicked image out of a bunch of images] in the favs array of that particular user. i have written below logic but it doesn't work.
for (let usrs of Object.values(localStorage)) {
JSON.parse(usrs).map(usr => {
// imgURL is the url of image marked as favorite
return usr.email === currentUsr ? localStorage.setItem(usr.favs,
imgURL) : null;
}
}
I really appreciate any help here.
Object.values(localStorage) returns an array of all values in local storage.
Since local storage keys and values are always stored as strings, you'll get an array of strings.
In your code, you are iterating on this array and then using JSON.parse() to convert each string to an object. The resultant object is user object such as { email: "test#test.com", password: "test123", favs: [] } which you can't apply map() method on
because it is not an array.
You can instead do as shown below.
// Get users from localStorage.
let users = JSON.parse(localStorage.getItem("defaultUsers"));
// Update image URL.
let modifiedUsers = users.map(user => {
// Not copying the reference to prevent mutating original array.
let favs = [...user.favs];
if (user.email === currentUsr) {
favs.push(imgURL);
}
return {
...user,
"favs": favs
};
});
// Update users in localStorage.
localStorage.setItem("defaultUsers", JSON.stringify(modifiedUsers));

Reading object property value in JavaScript object

I am trying to read the username property of the following JavaScript object and store it inside a variable.
[ RowDataPacket { username: 'admin', password: 'admin' } ]
It is being returned as a result object from an SQL query to a user database.
The returned object is called result
However, when I try to access its properties with
var sqlusername = result.username
or
var sqlusername = result.RowDataPacket.username
or
var sqlusername = result["username"]
or any other way to access the property,
the value of the variable var is always undefined.
How do I use the username and password properties of the object?
result is an array with one object in it. Use this:
result[0].username
Destructure the given result as
const [{ username, password }] = result;

Obtain an object after Objects Destructuring

I have the following object:
original = {userName: "pepe", pass: "password", otherFields: "blabla"}
I want to destructure it to obtain another object with only one field: userName
If I do:
const {userName} = original
console.log(JSON.stringify(userName)) ---> "pepe", but I would like to obtain {userName: "pepe"}
Or
var newObj = {userName} = original
console.log(JSON.stringify(newObj)) ---> {userName: "pepe", pass: "password", otherFields: "blabla"}
I would like to obtain {userName: "pepe"} after running JSON.stringify(...) because it makes me easier to do a fetch with this data in the body part.
The only way that I found to do that is the following:
const _body = {}
_body.userName = original.userName
body: (JSON.stringify(_body))
But when I have more fields to send in the body, I need to add lines to this code. Is there a better way to do what I want?
Essentially when you destructure the value from the object you're getting just that...the value. So in this case userName will return the string "pepe". You'll have to pass in a new object literal into your stringify call to get the desired result:
const original = { userName: "pepe", pass: "password", otherFields: "blabla" };
const { userName } = original;
console.log(JSON.stringify({ userName }));
If you are going to eventually need more properties, you could use the rest operator to do this.
const original = {userName: "pepe", pass: "password", otherFields: "blabla"}
const {pass, otherFields, ...rest} = original
console.log(JSON.stringify(rest))
Only thing is with this route, if you have properties inside original that you may not want into the stringify, you will have to add them to the destructuring so the "rest" operator doesn't pick them up.

Property not being added to JS object

So I am trying to add a field to a user object right before I return it and the property is not being added for some reason. Any thoughts?
returnUser = function(userRes) {
console.log(">POST /returnuser< Returning user w/ userId: " + userRes.userId + " deviceToken: " + userRes.deviceToken);
return Location.findOne({
users: {
$elemMatch: {
user: userRes.userId
}
}
}, function(error, response) {
userRes.currentLocation = response;
console.log(userRes);
return res.send(userRes);
});
};
So in the returnUser function I am searching the DB for the user's current location, adding that to the userRes object and then returning it. But when I log the userRes object it doesn't contain that property. Any issue with my code? userRes currently looks like this:
{ _id: 1,
createTime: 1428477183281,
deviceId: '982f24khsd',
deviceToken: 'kjs398fskjjg5fb43ds323',
firstName: 'Cat',
lastName: 'Man',
email: 'cat#mandu.com',
__v: 0,
users: [],
locations: [],
lngLat: [] }
As it turns out, that userRes object is actually a mongoose model instance returned from a mongoose query which is not mutable.
To fix this you can preferably call lean() which will give you a plain JS object instead of a full model instance.
Or if you don't have access to the query you can do something like:
mutableUserRes = JSON.parse(JSON.stringify(userRes));
Which copies the whole object but it is now a simple JS object instead of a mongoose model instance.

Json, displaying the usernames

Using
var arrayOfObjects = eval(photo.likes.data);
var objects = arrayOfObjects;
console.log(objects);
I get the code below is what console.log echos
json
[
Object
full_name: "marcab12"
id: "181407552"
profile_picture: "http://images.instagram.com/profiles/profile_181407550_75sq_1339521398.jpg"
username: "marcab12"
__proto__: Object
,
Object
full_name: "Ramage1992"
id: "21574723"
profile_picture: "http://images.instagram.com/profiles/profile_21574703_75sq_1349343851.jpg"
username: "ramage_1992"
__proto__: Object
]
How can I manage to show just the usernames on two lines as the javascipt I use seems to echo the 2 objects.
EDIT
$.each(likesperimage,function(index){
liked = likesperimage[index].username;
console.log(photo.id+' - '+liked);
});
I am assuming that this is a json array and you want to display the username for all the users in this array.The following code should work
$.each(arrayOfObjects,function(index)
{
console.log(arrayOfObjects[index].username);
});
here is the link to each in jquery api
http://api.jquery.com/jQuery.each/
Please test this code before using it.This is just a demonstration of how it can be done and there might be better ways to do it.

Categories

Resources