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.
Related
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);
I have an array with nested array
I want the data to append in a new array.
For the data extraction or filtration what method's i have to use, using library such as lodash
DATA
[
[
{
_id: 588d9b8a608f2a66c298849f,
email: 'sd#',
password: '$2a$10$6..L3c3tANi6ydt9gZbc1O6prPfUd3RB.ner5lilxRyEwo1lPsSoC',
isJobSeeker: true,
__v: 0,
lastName: 'shrestha',
firstName: 'manish',
isSeeker: true
}
],
[
{
_id: 588dbb4f7a48ce0d26cb99fd,
jobId: [Object],
seekerId: 588d9b8a608f2a66c298849f,
employerId: 588d7d6c0ec4512feb819825,
__v: 0,
}
]
]
REQUIRED DATA
[
{
_id: 588d9b8a608f2a66c298849f,
email: 'sd#',
password: '$2a$10$6..L3c3tANi6ydt9gZbc1O6prPfUd3RB.ner5lilxRyEwo1lPsSoC',
isJobSeeker: true,
__v: 0,
lastName: 'shrestha',
firstName: 'manish',
isSeeker: true
},
jobId: [{}, {}, {}] // ARRAY WITH OBJECTS
]
also i want to change the jobId key to other key of custom string as jobs
Following is my attempt:
console.log('Data filteration', data);
const filteredData = [];
filteredData.push(data[0][0]);
data[1].forEach((i) => {
filteredData[0].jobs = i.jobId
});
console.log('filteredData', filteredData);
First you should clean you data to have a better structure.
[
[
{ ... }
],
[
{ ... }
]
]
In this datastructure, its difficult to understand what does inner arrays signify. Instead you should use an object. That would define the purpose of array and make your code more readable.
var data=[[{_id:"588d9b8a608f2a66c298849f",email:"sd#",password:"$2a$10$6..L3c3tANi6ydt9gZbc1O6prPfUd3RB.ner5lilxRyEwo1lPsSoC",isJobSeeker:!0,__v:0,lastName:"shrestha",firstName:"manish",isSeeker:!0}],[{_id:"588dbb4f7a48ce0d26cb99fd",jobId:["test","test1"],seekerId:"588d9b8a608f2a66c298849f",employerId:"588d7d6c0ec4512feb819825",__v:0}]];
var cleanedData = {
userData: data[0],
userJobMap: data[1],
}
var result = cleanedData.userData.reduce(function(p,c){
if(c.isJobSeeker){
var job = cleanedData.userJobMap.filter(x=> x.seekerId === c._id);
// To copy object and not reference
var t = Object.assign({}, c, { jobId: job[0].jobId });
p.push(t)
}
return p
}, [])
console.log(result)
References
Array.map is a tool that iterates over all elements and return different value say a single property of return double value of all numbers in array. Note, this will yield an array of same size.
Array.filter on the other hand is use to filter array based on condition. This will return a subset of original data but elements will be same. You cannot change element structure.
Array.reduce is a tool that address cases where you need to return selected elements with parsed value. You can achieve same by chaining .filter().map() but then its an overkill as it would result in O(2n).
Object.assign In JS objects are passed by reference. So if you assign an object to a variable, you are not copying entire object, but only reference. So it you change anything in this variable, it will also reflect in original object. To avoid this, you need to copy value. This is where Object.assign comes. Note, its not supported by old browsers. For them you can check following post - What is the most efficient way to deep clone an object in JavaScript?
Note: All array functions are part of functional programming paradigm and are used to make your code more readable and concise but they come at an expense of performance. Traditional for will always perform faster then them. So if you want to focus on performance, always try to use for (though difference is very small but can add up for multiple cases and become substantial)
I want to search names in a guest list array that may contain multiple guest objects. This array of objects is stored among other properties in a mongo db collection named "Guests" in my meteor project .
SimpleSchema snippet:
guestList: {
type: [Object],
label: "Guest List"
}
example guest object:
var newGuest = [{
firstName: "John",
lastName: "Doe"
},
{
firstname: "Jane",
lastName: "Doe"
}];
It is being inserted successfully against the SimpleSchema, what I need help with now is how I can search the names if my complete object looks something like this is the collection?
{
guestList: newGuests,
address: "123 4th St. NE",
phone: "555-555-5555",
email: "jon#doe.com"
}
Now let's say I have multiple entries with possible multiple guests within each guestList property but I want to get the entry that has the firstName of "Jane" in its guestList property.
I've tried Guests.find({ guestList: { firstName : "Jane" } }).fetch(); but I'm not getting any results.
I also tried Guests.find({guestList[0].firstName: "Jane"}).fetch(); with no results as well.
Any help would be greatly appreciated!
It sounds like what you are looking for is the $elemMatch query operator. Take a look at how to use it here too. I suggest writing your query like so:
Guests.find({
guestList: {
$elemMatch: {
firstName: 'Jane'
}
}
});
The reason why you would not use the first query that you specified is because it is trying to match on a single embedded document rather than on an array of documents. Also, the reason why you would not use the second query that you specified is because it is trying to match only on the first embedded document in an array of documents, but obviously you would want to check all of the embedded documents in an array.
$elemMatch
Guests.find({ guestList: { $elemMatch: { firstName: "Jane" }}});
I have the following data structure for my users in my mongodb:
{
_id: "someId",
profile: {
username: "oliv",
friendRequests: [
{ fromUserId: "anId", accepted: false, created: "someDate"},
{ fromUserId: "otherId", accepted: true, created: "otherDate"}
]
}
I'd like to retrieve the user objects that are referenced in my logged user's friendsRequested.
So I tried something like this:
Meteor.users.find({_id: {$in: Meteor.user().profile.friendRequests.fromUserId}});
// FYI: Meteor.users is the collection and Meteor.user() retrieves the current user
But it's not working. I'm assuming it's because of the nested array.
Is there any way of telling mongo to iterate through the fromUserId or something?
Thanks
Change your query to:
Meteor.users.find({_id: {$in: _.pluck(Meteor.user().profile.friendRequests, 'fromUserId') }});
Reasoning:
friendRequests is an array of objects, and $in wants an array of strings(the ids), using _.pluck you're able to pass an array of objects, and tell _ to only return the field fromUserId for each object in the array.
Question in comment ("what if I only want to get the ids from friend requests where "accepted" is false?"):
_.pluck(
_.filter(Meteor.user().profile.friendRequests, function (req) {
return !req.accepted;
}),
'fromUserid'
);
Underscore filter docs
Basically I got my app up an running but I'm stuck with a problem: if I pass an object that contains an empty array to be saved, the array is not saved into the db. I'm not sure this is a problem in js or the mongo driver, but in order to save the empty array I need to pass the array like so: products: [''].
This is the structure of my mongo document:
_id: ObjectId(...),
name: 'String',
subcategories: [
{
subcategory: 'string',
products: [
{
name: 'string'
price: integer
}
]
}
]
So in my front-end I'm grabbing the whole document through an ajax call pushing a new object into the subcategories array. The new object looks like this:
{subcategory:'string', products:['']}
And this works okay until I need to insert a new object inside the array: Because I've grabbed the whole object, pushed the new object to the array, the previous one looks like this:
{subcategory: 'string'}
Having lost the mention to products:[] array in the process.
How can I get around this? I need to be able to have empty arrays in my object.
EDIT
What I did on front end: Got the whole object with $.get which returned:
var obj =
_id: ObjectId(...),
name: 'String',
subcategories: [
{
subcategory: 'Subcategory1',
products: [
{
name: 'string'
price: integer
}
]
}
];
Then on the front end I've pushed the new object category inside the subcategories array:
data.subcategories.push({subcategory: 'Subcategory2', products: ['']})
Where subcat was a string with the category name. On my db I could see that I've successfully added the object:
var obj =
_id: ObjectId(...),
name: 'String',
subcategories: [
{
subcategory: 'Subcategory1',
products: [
{
name: 'string'
price: integer
}
]
},
{
subcategory: 'Subcategory2'
products: []
}
];
The problem was when I wanted to add another subcategory, the previous one return empty:
var obj =
_id: ObjectId(...),
name: 'String',
subcategories: [
{
subcategory: 'Subcategory1',
products: [
{
name: 'string'
price: integer
}
]
},
{
subcategory: 'Subcategory2'
},
{
subcategory: 'Subcategory3'
products: []
},
];
Because at some point the empty array was removed from the object. Like I said, I did fix this in the front end, so the error jade was throwing has been addressed, but I still find odd that the products: [] was being removed from the document.
I'm new to MongoDb and node, not to mention that I'm also new with JS, so it might well be a feature that I'm unaware of.
When passing empty arrays to Mongo they are interpreted as empty documents, {}. Zend Json encoder will interpret them as empty arrays []. I understand that it's not possible to tell which one is correct.
Incase of empty arrays try posting as
Array[null];
instead of Array[];
This will be working fine
When passing empty arrays to Mongo they are interpreted as empty documents, {}. Zend Json encoder will interpret them as empty arrays []. I understand that it's not possible to tell which one is correct.
In my view it's more logical that the actual php array (when empty) is interpreted as an array in MongoDB. Although that will require something else to identify empty documents it's still more logical than the current behaviour.
A possible solution would be to introduce a new object, MongoEmptyObject (or using the stdObj) whenever one want to introduce an empty object.
Meanwhile, a workaround is to detect empty arrays in php, and inject a null value $arr[0] = null;
Then the object will be interpreted as an empty array in mongo.
The workaround works both in PHP and in the mongo console. Question: does json allow for arrays with null values? If so, then the workaround is a sign of another bug.
PHP:
if (is_array($value) && empty($value))
{ $value[0] = null; }
Mongo Console:
var b =
{hej:"da", arr: [null]}
db.test.save(b);
db.test.find();
{"_id" : "4a4b23adde08d50628564b12" , "hej" : "da" , "arr" : []}