How can I apply aggregate on array of objects? - javascript

I have this complicated data in MongoDB, I want to reconstruct it into something like the second JSON, I tried both MongoDB aggregate and javascript spread, but I couldn't figure it out.
Original Data
[
{
"_id": "61ff24b2db73094dd3029c7e",
"TeamName": "GoodTeam",
"TeamImage": "Avatar",
"TeamMember": [
{
"name": "Aimee",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "test2#gmail.com",
"timezone": "PST",
"_id": "61ff25fcd2a0b9e13ee8989c"
},
{
"name": "Kai",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "school021195#gmail.com",
"timezone": "PST",
"_id": "61ff3114d3d343bd673f5ad3"
},
{
"name": "Iren",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "test1#gmail.com",
"timezone": "AKST",
"_id": "61ff3114d3d343bd673f5ad4"
}
],
"createdAt": "2022-02-06T01:30:26.893Z",
"updatedAt": "2022-02-06T02:23:16.660Z",
"__v": 0
}
]
Reconstruct Data
[
{
"timezone":"PST",
"TeamMember":[
{
"name": "Aimee",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "test2#gmail.com",
"timezone": "PST",
"_id": "61ff25fcd2a0b9e13ee8989c"
},
{
"name": "Kai",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "school021195#gmail.com",
"timezone": "PST",
"_id": "61ff3114d3d343bd673f5ad3"
},
{
"timezone":"AKST",
"TeamMember":[
{
"name": "Iren",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "test1#gmail.com",
"timezone": "AKST",
"_id": "61ff3114d3d343bd673f5ad4"
}
]
}
]
And how should I deal with this kind of data reconstruction in the front-end or back-end? Which one is better practice?

You can always create a custom transformer for converting one JSON to another JSON and I would suggest you to let the back-end handle this responsibility.
Below is one example using Javascript.
const firstJson = `[
{
"_id": "61ff24b2db73094dd3029c7e",
"TeamName": "GoodTeam",
"TeamImage": "Avatar",
"TeamMember": [
{
"name": "Aimee",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "test2#gmail.com",
"timezone": "PST",
"_id": "61ff25fcd2a0b9e13ee8989c"
},
{
"name": "Kai",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "school021195#gmail.com",
"timezone": "PST",
"_id": "61ff3114d3d343bd673f5ad3"
},
{
"name": "Iren",
"image": "https://i.imgur.com/HeIi0wU.png",
"email": "test1#gmail.com",
"timezone": "AKST",
"_id": "61ff3114d3d343bd673f5ad4"
}
],
"createdAt": "2022-02-06T01:30:26.893Z",
"updatedAt": "2022-02-06T02:23:16.660Z",
"__v": 0
}
]`;
const firstJsonObj = JSON.parse(firstJson);
const map = new Map();
for(let i =0;i<firstJsonObj.length;i++){
for(let j =0;j<firstJsonObj[i].TeamMember.length;j++){
let timezone = firstJsonObj[i].TeamMember[j].timezone;
if(map.has(timezone)){
const team = map.get(timezone);
team.push(firstJsonObj[i].TeamMember[j]);
map.set(timezone,team);
}
else{
map.set(timezone,[firstJsonObj[i].TeamMember[j]])
}
}
}
const secondJson = Array.from(map,function(element){
const [key,value] = element;
return {
timezone : key,
TeamMember : value
}
});
console.log(JSON.stringify(secondJson));
EDIT:
If you want query data from mongodb itself you can use below query to get the output
db.collection.aggregate([
{
"$unwind": "$TeamMember"
},
{
"$group": {
"_id": {
"timezone": "$TeamMember.timezone"
},
"TeamMember": {
"$push": "$$ROOT.TeamMember"
}
}
},
{
"$project": {
"_id": 0,
"timezone": "$_id.timezone",
"TeamMember": 1
}
}
])

It is better to do it in the backend and recommended.
You can achieve this by multiple ways in the backend using mongo aggregation framework. It is very powerful framework with multiple operators to handle these kind of data.

Related

Merge multiple Json objects while nesting them

I am currently developing an endpoint where I want to return one object from 4 different tables. I get the record of each table in JSON format from sequelize. I have a location, service, staff, and Tenant. How can I merge them into one object but nested.
For example:
The data I get from sequelize for staff:
{
"id": 2,
"profession": "Dentist",
"note": "Good Man",
"holidays": "Saturday",
"specialDays": null,
"createdAt": "2023-01-27T14:23:52.000Z",
"updatedAt": "2023-01-27T14:23:52.000Z",
}
All other data are in a similar format. But I want to merge them to return something like:
{ staff:{
"id": 2,
"profession": "Dentist",
"note": "Good Man",
"holidays": "Saturday",
"specialDays": null,
"createdAt": "2023-01-27T14:23:52.000Z",
"updatedAt": "2023-01-27T14:23:52.000Z",},
location:{
"id": 1,
"name": "Branch 1",
"address": "37 Automatic Handling",
"description": "This is our main branch",
"latitude": "564233",
"longtitude": "4441256",
"visible": true,
"createdAt": "2023-01-27T14:05:37.000Z",
"updatedAt": "2023-01-27T14:05:37.000Z",
}
}
Just make an object yourself
// (inside of an async function)
const location = await // sequelize code to get this info
const service = await // sequelize code to get this info
const staff = await // sequelize code to get this info
const tenant = await // sequelize code to get this info
return res.json({
location,
service,
staff,
Tenant: tenant, // remove "Tenant: " if the capital was a typo or you don't care
});
This should work
const staff = {
"id": 2,
"profession": "Dentist",
"note": "Good Man",
"holidays": "Saturday",
"specialDays": null,
"createdAt": "2023-01-27T14:23:52.000Z",
"updatedAt": "2023-01-27T14:23:52.000Z",
};
const location1 = {
"id": 1,
"name": "Branch 1",
"address": "37 Automatic Handling",
"description": "This is our main branch",
"latitude": "564233",
"longtitude": "4441256",
"visible": true,
"createdAt": "2023-01-27T14:05:37.000Z",
"updatedAt": "2023-01-27T14:05:37.000Z",
};
const mergedObject = { staff, location1 };
console.log(mergedObject);

Unable to extract the array field from JSON file. Instead my code returns "{}"

I want to return (res.json) the array of chats in this model but when I am trying to do so I am getting "{}".
On the other hand, when I am printing other fields like email or first_name, I am getting the results.
However, I guess the problem is only with arrays.
I am using MongoDB to store data and Postman for requests
PLEASE HELP!
Here is my JSON model.
{
"_id": "5f0d5ea45eeeaa3730eaf96c",
"first_name": "Test_firstName",
"last_name": "Test_lastName",
"email": "test#email.com",
"password": "$2b$10$B8EDo3KkJZ9PjGveWfouM.1XhaPSx9xrM3c6Mk2HC02AUNnO99Of.",
"address": "Home",
"chats": [
{
"id": "985234e2-86c6-4375-968a-96661c37ec32",
"name": "Community",
"messages": [
{
"id": "35c7bf4d-e556-40bd-9429-16e436c599f4",
"time": "11:10",
"message": "Hi",
"sender": "user1"
},
{
"id": "a74ad9ba-44b9-43af-90a0-cf9480d9a748",
"time": "11:11",
"message": "hey",
"sender": "user2"
}
]
}
],
"createdAt": "2020-07-14T07:28:36.148Z",
"updatedAt": "2020-07-14T07:28:36.148Z",
"__v": 0
}
Here is my code to find a chat from my model.
Please have a look at the lines with "<"
const find_chat = (req, res, next) => {
let email = req.body.email;
let chatId = req.body.chatId;
User.findOne({ email: email })
.then(async (response) => {
> let x = [];
> x = response.chats;
> res.json({
> response,
> });
})
.catch((error) => {
res.json({
message: "An error occured",
});
});
};
Here is the expected output
{
[
{
"id": "35c7bf4d-e556-40bd-9429-16e436c599f4",
"time": "11:10",
"message": "Hi",
"sender": "Advait"
},
{
"id": "a74ad9ba-44b9-43af-90a0-cf9480d9a748",
"time": "11:11",
"message": "hey",
"sender": "sharma"
}
]
}
You could try as this:
const data = {
"_id": "5f0d5ea45eeeaa3730eaf96c",
"first_name": "Test_firstName",
"last_name": "Test_lastName",
"email": "test#email.com",
"password": "$2b$10$B8EDo3KkJZ9PjGveWfouM.1XhaPSx9xrM3c6Mk2HC02AUNnO99Of.",
"address": "Home",
"chats": [
{
"id": "985234e2-86c6-4375-968a-96661c37ec32",
"name": "Community",
"messages": [
{
"id": "35c7bf4d-e556-40bd-9429-16e436c599f4",
"time": "11:10",
"message": "Hi",
"sender": "user1"
},
{
"id": "a74ad9ba-44b9-43af-90a0-cf9480d9a748",
"time": "11:11",
"message": "hey",
"sender": "user2"
}
]
}
],
"createdAt": "2020-07-14T07:28:36.148Z",
"updatedAt": "2020-07-14T07:28:36.148Z",
"__v": 0
}
let messages = data.chats[0].messages;
console.log(messages)
As per the later query , change it to
let x = JSON.stringify(response.chats[0].messages);
res.json({
response});

Checking a value in a nested JSON using Postman

I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this
"result": [
{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
},
I am trying to test whether my response body has "name":"India" and the "game" with "some_game_id1" contains the "name":"cricket".
I went through this link where the answer is to have an array for "name"created and then check within the array whether the array contains the value. I tried this but my code fails.
Also, I tried searching the element by the index within the JSON body using this -
var searchJSON = JSON.parse(responseBody);
tests["name contains India"] = searchJSON.result.name[0]==="India";
But this also fails. I tried using the .value appended with the second line of above code, but it also fails. How can I check this thing?
You need to put [0] after result (which is an array) rather than name (which is a string).
Also, use a regular expression to check whether the name contains 'India', because using === only checks if the name is exactly India.
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
Demo Snippet:
var responseBody = `{
"result": [{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
}
]
}`
var tests = {}
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
console.log(tests) //=> { "name contains India": true }

Waterline Sails JS doesn't work

I've using associations in Sails JS. I've been building an ecommerce app, in which multiple models are associated to one another, but one of associated doesn't work.
In my controller, I'm trying like this:
'synchronize' : function(req,res,next){
var owner = req.param('owner'),
store = req.param('store'),
items = req.param('items'),
localCart = {
'items' : items,
'owner' : owner,
'store' : store
},
updatedCart = {};
// get cart first
PosCart.findOrCreate({
'owner' : owner,
'store' : store
},localCart)
.populate('items')
.then(function(serverCart){
if(!serverCart) throw 'Kesalahan Sistem';
// update server cart
_.each(localCart.items, function(item,index){
var _server_index = {};
// check if product exist
_server_index =_.findIndex(serverCart.items, function(_item){
return _item.product === item.product.id &&
_item.productCustomize === item.productCustomize.id &&
_.isEqual(_item.attributes,item.attributes)
});
// product already exist but have different quantity
if(_server_index > -1){
item.quantity = (item.quantity > serverCart.items[_server_index].quantity)?
item.quantity : serverCart.items[_server_index].quantity ;
serverCart.items[_server_index] = _.clone(item);
}else{
// this is new items
serverCart.items.push(_.clone(item));
}
});
// update cart then
return PosCart.update(serverCart.id, serverCart);
})
.then(function(carts){
if(!carts) throw 'Kesalahan Sistem';
// return new updated cart
// 2 level populate
updatedCart = _.clone(carts[0]);
return [
PosCart.findOne(updatedCart.id).populate('items'),
PosItem.find({'id':updatedCart.item}).populate('product'),
PosItem.find({'id':updateCart.item}).populate('productCustomize')
];
})
.spread(function(cart,items){
if(!cart) throw 'kesalahan sistem'
_.each(cart.items,function(item,index){
cart.items[index] = _.find(items,function(_item){
return _item.id === item.id;
});
});
return res.json(cart);
})
.catch(function(error){
next(error);
});
}
And In My model, I'm trying like this
PosCart.js
attributes: {
items : { collection : 'PosItem', via : 'cart' },
// owner
owner : { model : 'CrmCustomer' },
// store referrer
store : { model : 'SystemStore' }
}
PosItem.js
attributes: {
product : { model : 'PosProduct' },
productCustomize : { model : 'PosCustomProduct' },
variant : { model : 'PosProductVariant' },
attributes : { type : 'json', defaultsTo : {} },
quantity : { type : 'integer', defaultsTo : 1 },
// owner
cart : { model : 'PosCart' },
wishlist : { model : 'PosWishlist' }
}
The PosItem.find({'id':updateCart.item}).populate('productCustomize') doesn't populate in PosItem. If I try to add to cart the 'productcustom' property, like product, it'll show it's ID.
[
{
"product": {
"display": "5636fe51effd3d4508d16cc8",
"materials": [],
"store": "5636fd43effd3d4508d16cb5",
"name": "Penny",
"basePrice": 250000,
"category": "5636fe14effd3d4508d16cc7",
"attributes": {
"Bahan": [
"Kulit"
],
"Ukuran": [
"38"
]
},
"desc": "Lorem ipsum dolor sit amet",
"published": true,
"createdAt": "2015-11-02T06:10:25.296Z",
"updatedAt": "2015-11-02T06:10:25.395Z",
"id": "5636fe51effd3d4508d16cc9"
},
"variant": {
"name": "5636fe51effd3d4508d16cc9-Bahan:Kulit-Ukuran:38",
"Bahan": "Kulit",
"Ukuran": "38",
"product": "5636fe51effd3d4508d16cc9",
"additionalPrice": 0,
"createdAt": "2015-11-02T06:10:25.508Z",
"updatedAt": "2015-11-02T06:10:25.508Z",
"id": "5636fe51effd3d4508d16cca"
},
"cart": {
"store": "5632e638954e0b843f285faa",
"createdAt": "2015-11-02T06:13:28.708Z",
"updatedAt": "2015-11-02T06:13:28.738Z",
"id": "5636ff08effd3d4508d16cce"
},
"quantity": 1,
"attributes": {
"Bahan": "Kulit",
"Ukuran": "38"
},
"createdAt": "2015-11-02T06:13:28.757Z",
"updatedAt": "2015-11-02T06:13:28.757Z",
"id": "5636ff08effd3d4508d16cd0"
},
{
"variant": {
"name": "5637016deffd3d4508d16cdc-Bahan:Kulit-Soles:Outsole-Ukuran:38",
"Bahan": "Kulit",
"Soles": "Outsole",
"Ukuran": "38",
"product": "5637016deffd3d4508d16cdc",
"additionalPrice": 25000,
"createdAt": "2015-11-02T06:23:41.862Z",
"updatedAt": "2015-11-02T06:24:53.995Z",
"display": [
{
"zoom": "file/65e1d275-c3a7-4502-a0fe-6f5ac299d00d.jpg",
"gallery": "file/ecbf0705-88ce-41dc-8ba2-4755041b623e.jpg",
"thumbnail": "file/0db0e9e8-9294-4df0-b173-7d6de822786a.jpg",
"active": true
}
],
"id": "5637016deffd3d4508d16cdd"
},
"cart": {
"store": "5636fd43effd3d4508d16cb5",
"owner": "56370d92509c2c470a3d33ac",
"createdAt": "2015-11-02T07:15:47.026Z",
"updatedAt": "2015-11-02T07:16:11.749Z",
"id": "56370da3509c2c470a3d33af"
},
"quantity": 1,
"attributes": {
"Bahan": "Kulit",
"Soles": "Outsole",
"Ukuran": "38"
},
"createdAt": "2015-11-02T07:16:11.809Z",
"updatedAt": "2015-11-02T07:16:11.809Z",
"id": "56370dbb509c2c470a3d33b1"
}
]
Anyone can help me to solve this to be result at the bottom? :)
[
{
"product": {
"display": "5636fe51effd3d4508d16cc8",
"materials": [],
"store": "5636fd43effd3d4508d16cb5",
"name": "Penny",
"basePrice": 250000,
"category": "5636fe14effd3d4508d16cc7",
"attributes": {
"Bahan": [
"Kulit"
],
"Ukuran": [
"38"
]
},
"desc": "Lorem ipsum dolor sit amet",
"published": true,
"createdAt": "2015-11-02T06:10:25.296Z",
"updatedAt": "2015-11-02T06:10:25.395Z",
"id": "5636fe51effd3d4508d16cc9"
},
"productCustomize": {
"display": "5636fe51effd3d4508d16dd9",
"materials": [],
"store": "5636fd43effd3d4508d16cb5",
"name": "Beefroll",
"basePrice": 250000,
"category": "5636fe14effd3d4508d16cc7",
"attributes": {
"Bahan": [
"Kulit"
],
"Ukuran": [
"38"
]
},
"variant": {
"name": "5636fe51effd3d4508d16cc9-Bahan:Kulit-Ukuran:38",
"Bahan": "Kulit",
"Ukuran": "38",
"product": "5636fe51effd3d4508d16cc9",
"additionalPrice": 0,
"createdAt": "2015-11-02T06:10:25.508Z",
"updatedAt": "2015-11-02T06:10:25.508Z",
"id": "5636fe51effd3d4508d16cca"
},
"cart": {
"store": "5632e638954e0b843f285faa",
"createdAt": "2015-11-02T06:13:28.708Z",
"updatedAt": "2015-11-02T06:13:28.738Z",
"id": "5636ff08effd3d4508d16cce"
},
"quantity": 1,
"attributes": {
"Bahan": "Kulit",
"Ukuran": "38"
},
"createdAt": "2015-11-02T06:13:28.757Z",
"updatedAt": "2015-11-02T06:13:28.757Z",
"id": "5636ff08effd3d4508d16cd0"
},
{
"variant": {
"name": "5637016deffd3d4508d16cdc-Bahan:Kulit-Soles:Outsole-Ukuran:38",
"Bahan": "Kulit",
"Soles": "Outsole",
"Ukuran": "38",
"product": "5637016deffd3d4508d16cdc",
"additionalPrice": 25000,
"createdAt": "2015-11-02T06:23:41.862Z",
"updatedAt": "2015-11-02T06:24:53.995Z",
"display": [
{
"zoom": "file/65e1d275-c3a7-4502-a0fe-6f5ac299d00d.jpg",
"gallery": "file/ecbf0705-88ce-41dc-8ba2-4755041b623e.jpg",
"thumbnail": "file/0db0e9e8-9294-4df0-b173-7d6de822786a.jpg",
"active": true
}
],
"id": "5637016deffd3d4508d16cdd"
},
"cart": {
"store": "5636fd43effd3d4508d16cb5",
"owner": "56370d92509c2c470a3d33ac",
"createdAt": "2015-11-02T07:15:47.026Z",
"updatedAt": "2015-11-02T07:16:11.749Z",
"id": "56370da3509c2c470a3d33af"
},
"quantity": 1,
"attributes": {
"Bahan": "Kulit",
"Soles": "Outsole",
"Ukuran": "38"
},
"createdAt": "2015-11-02T07:16:11.809Z",
"updatedAt": "2015-11-02T07:16:11.809Z",
"id": "56370dbb509c2c470a3d33b1"
}
]
You have so many fields! :-)
My suggestion to find the problem would be to start backwards and then get to where you want.
Go to https://github.com/balderdashy/waterline-docs/blob/master/models/associations/associations.md and see if you can make the basic association model work.
Then step by step start adding your complexity. If you follow this gradual approach eventually you will stumble upon where the problem lies.
Good luck!

JavaScript - Loop JSON array and match string in subarray

I have JSON array with subarrays and I want to loop it and find if username of user is for example 'admin'. If so then create JSON array contains data belonging to user 'admin' (region, sport, city etc). I don't have idea how to find it in loop and then slice it. I'm sorry for stupid question but I'm a little lost.
This is JSON array with structure what I have:
[
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
},
{
"_id": "552010740628cab002b3a700",
"region": {
"_id": "551e67b6d8f1afa01bd8652f",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "Bill",
"lastName": "Foo",
"username": "bill_foo",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e5e01abb74a8423410b88",
"nazev": "Hockey"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "some_title",
"created": "2015-04-04T16:25:24.733Z"
}
]
Edit:
the expected result of user 'admin' is then:
[
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
}]
Loop through the array and pull out each item with a user with a username of admin:
var result = [];
var nameToSearchFor = 'admin';
for(var index = 0; index < arr.length; index++)
{
var item = arr[index];
if(item.user.username === nameToSearchFor)
{
result.push(item);
}
}
One solution to your problem is to search for the index that resides the admin username. In your case is at the 0 index of the json array provided. So you can get the entire object by the index, like this:
var i = 0;
for(; i< json.length; i++){
if(json[i].user.username === "admin") break;
}
With that now you can get the object with the admin data. Like this:
json[i].user.firstName
Check this plunk here
EDIT
If you want just to get that slice to a new array perhaps then you can just slice that piece of the json array, now that you have the index.
var newArray = json.slice(i, i+1);
You can use an open source project like jinqJs to perform SQL like queries on arrays.
var data = [
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
},
{
"_id": "552010740628cab002b3a700",
"region": {
"_id": "551e67b6d8f1afa01bd8652f",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "Bill",
"lastName": "Foo",
"username": "bill_foo",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e5e01abb74a8423410b88",
"nazev": "Hockey"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "some_title",
"created": "2015-04-04T16:25:24.733Z"
}
];
var result = jinqJs()
.from(data)
.where(function(row){return row.user.username==='admin';})
.select();
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre><br><br>';
<script src="https://rawgit.com/fordth/jinqJs/master/jinqjs.js"></script>

Categories