How to remove multi nested object in javascript using id - javascript

Declaration of id
var id = 3;
I want to update this object
var obj = {"comments" : {
"commentedBy" : "test",
"date" : "",
"comment" : "Hello world",
"subComments" : {
"commentedBy" : "jaril 2",
"date" : "",
"comment" : "Hello world inside dark",
"subComments" : {
"commentedBy" : "jaril 3",
"date" : "",
"comment" : "wow working great",
"subComments" : {
"commentedBy" : "jaril 4",
"date" : "",
"comment" : "wow working great",
"commentId" : 4
},
"commentId" : 3
},
"commentId" : 2
},
"commentId" : 1
},
"dueDate" : "",
"createdDate" : "",
"lastUpdated" : "",
"checkList" : [],
"position" : 2,
"status" : "active"
}
}
Function is this
function deleteCommentId(comments){
if (comments.commentId == id)){
delete comments;
return comments;
}
if (comments.subComments) {
deleteCommentId(comments.subComments);
}
return comments;
}
Function Object is this
if(id == 1){
result[0].comments = {};
} else {
deleteCommentId(obj.comments);
}
console.log("final object==>", obj);
I want output like this
{"comments" : {
"commentedBy" : "test",
"date" : "",
"comment" : "Hello world",
"subComments" : {
"commentedBy" : "jaril 2",
"date" : "",
"comment" : "Hello world inside dark",
"commentId" : 2
},
"commentId" : 1
},
"dueDate" : "",
"createdDate" : "",
"lastUpdated" : "",
"checkList" : [],
"position" : 2,
"status" : "active"
}
}
Any help would be appreciated
Note: I want to remove nested subcomments object using id if I pass
id=3 then it should remove subcomment of 2, How can I remove subcomments of 2 if id = 3

The function below should do it.
(I removed the irrelevant parts or your object to make things a bit easier to read.)
var obj = {
"comments": {
"subComments": {
"subComments": {
"subComments": {
"commentId": 4
},
"commentId": 3
},
"commentId": 2
},
"commentId": 1
}
};
function deleteCommentId(comments, id) {
if (comments.subComments) {
if (comments.subComments.commentId === id) {
delete comments.subComments;
} else {
deleteCommentId(comments.subComments, id);
}
}
}
deleteCommentId(obj.comments, 3);
console.log(obj);

var id = 3;
var obj = {"comments":{"commentedBy":"test","date":"","comment":"Hello world","subComments":{"commentedBy":"jaril 2","date":"","comment":"Hello world inside dark","subComments":{"commentedBy":"jaril 3","date":"","comment":"wow working great","subComments":{"commentedBy":"jaril 4","date":"","comment":"wow working great","commentId":4},"commentId":3},"commentId":2},"commentId":1},"dueDate":"","createdDate":"","lastUpdated":"","checkList":[],"position":2,"status":"active"}
function deleteCommentId(comments, id) {
if (comments.subComments) {
if (comments.subComments.commentId === id) {
delete comments.subComments;
} else {
deleteCommentId(comments.subComments, id);
}
}
}
deleteCommentId(obj.comments, id);
console.log("final object==>",obj);
var expectedJSON = {"comments":{"commentedBy":"test","date":"","comment":"Hello world","subComments":{"commentedBy":"jaril 2","date":"","comment":"Hello world inside dark","commentId":2},"commentId":1},"dueDate":"","createdDate":"","lastUpdated":"","checkList":[],"position":2,"status":"active"}
console.log("Output match: ",JSON.stringify(obj) == JSON.stringify(expectedJSON));

Related

How to remove some property and characters in JSON response

I am trying to remove some property of a JSON response.
I would like to remove this part of the response (first part) :
{
"en" : 10,
"left" : false,
"right" : false,
"result" :
And remove too the last character of the response (last part) :
"}"
I have tried different ways to do this but none of them work as I would like them to.
var object_delete = ['en','left','right','result'];
for(i in object_delete){
var data = JSON.parse(JSON.stringify(data).replace(object_delete[i], ""));
}
I expect the output :
[ {
"type1" : "string data",
"type2" : "string data",
"type3" : {
"name" : "string data"
},
"red" : {
"path" : "string data",
"path2" : null,
"path3" : null,
"path4" : null
}
} ]
But the actual output is :
{
"en" : 2,
"left" : false,
"right" : false,
"result" : [ {
"type1" : "string data",
"type2" : "string data",
"type3" : {
"name" : "string data"
},
"red" : {
"path" : "string data",
"path2" : null,
"path3" : null,
"path4" : null
}
} ]
}
Anyone have any idea how this can be done?
You could try something like this:
const entry = {
"entries" : 10,
"left" : false,
"right" : false,
"result" : [
{
"type1" : "string data",
"type2" : "string data",
"type3" : "string data",
"type4" : "string data",
"type5" : "string data",
"type6" : {
"name" : "string data"
},
"red" : {
"path" : "string data",
"path2" : null,
"path3" : null,
"path4" : null
}
}
]
};
const output = [...entry["result"]];
console.log(JSON.stringify(output));
// [{"type1":"string data","type2":"string data","type3":"string data","type4":"string data","type5":"string data","type6":{"name":"string data"},"red":{"path":"string data","path2":null,"path3":null,"path4":null}}]

Mongodb mapreduce Join 2 collections

I have 2 collections and I am new to Mongo MapReduce concept.
My collection Value looks like this
{
"_id" : ObjectId("5bc4f20e1a80d2045029ccb7"),
"name" : "Title 1",
"value" : "value 1 for title 1"
}
{
"_id" : ObjectId("5bc4f20e1a80d2045029ccb8"),
"name" : "Title 1",
"value" : "Value 2 for title1. "
}
{
"_id" : ObjectId("5bc4f20e1a80d2045029ccb9"),
"name" : "Title 2",
"value" : " Definitely a motivational text!"
}
{
"_id" : ObjectId("5bc4f20e1a80d2045029ccba"),
"name" : "Title 2",
"value" : "It's tough but I'm carrying on. "
}
Other collection Details look like:
{
"_id" : ObjectId("5bc4f2361a80d2045029d05b"),
"name" : "Title 1",
"totalValues" : 6.0000000000000000,
"link": "Link1",
"description" : "Some More Text to Make title 1 look better"
}
{
"_id" : ObjectId("5bc4f2361a80d2045029d2eb"),
"name" : "Title 2",
"totalValues" : 2,
"link": "Link2",
"description" : "Some More Text to Make title 2 look better"
} ...
I want the output result as
{
“name” : “XXXXXXXX”,
“comments” : [ {“value”: “XXXXXXX”}, {“value”: “YYYYYYYY”}],
“totalValues” : 2,
“link”: “XXXXXXXXXX”,
“description”: “XXXXXXXXXXXXXXXXXX”
}
with the following output document. Please help.
I have tried following code:
var mapDetails = function(){
var output = {name: this.name,totalValues :this.totalValues, description : this.description, link :this.link}
emit(this.name, output);
};
var mapGpas = function() {
emit(this.name,{name:this.name, value:this.value, totalValues:0, description: 0, link: 0});
};
var r = function(key, values) {
var outs = { name: 1,value: 1, description: 0,totalValues:0, link: 0};
values.forEach(function(v){
outs.name = v.name;
if (v.value == 0) {
outs.description = v.description;
outs.totalValues = v.totalValues;
outs.link = v.link;
}
});
return outs;
};
res = db.Value.mapReduce(mapGpas, r, {out: {reduce: 'joined'}})
res = db.Details.mapReduce(mapDetails, r, {out: {reduce: 'joined'}})
db.joined.find().pretty()

How to update document in Mongodb collection with a field value from another collection

I have two collections
1) Floorplan_backup.
The structure of the document looks like :-
{
"_id" : ObjectId("5877e18a88db272b578572bd"),
"floorplans" : [
{
"name" : "Campus Center - Atrium",
"uuid" : NumberLong(3),
"cameras" : []
},
{
"name" : "Campus Center - Bridge ",
"uuid" : NumberLong(4),
"cameras" : []
},
{
"name" : "Campus Center - Top",
"uuid" : NumberLong(5),
"cameras" : []
},
{
"name" : "Performance Dining Hall",
"uuid" : NumberLong(6),
"cameras" : []
},
{
"name" : "Main Kitchen",
"uuid" : NumberLong(7),
"cameras" : []
},
{
"name" : "OrgChart - Board of Trustees",
"uuid" : NumberLong(8),
"cameras" : []
},
{
"name" : "OrgChart - Academic Affairs",
"uuid" : NumberLong(9),
"cameras" : []
},
{
"name" : "OrgChart - Admissions",
"uuid" : NumberLong(10),
"cameras" : []
},
{
"name" : "OrgChart - Athletics",
"uuid" : NumberLong(11),
"cameras" : []
},
{
"name" : "OrgChart - Financial",
"uuid" : NumberLong(14),
"cameras" : []
},
{
"name" : "OrgChart - HR",
"uuid" : NumberLong(15),
"cameras" : []
},
{
"name" : "OrgChart - Institutional",
"uuid" : NumberLong(16),
"cameras" : []
},
{
"name" : "OrgChart - IT",
"uuid" : NumberLong(17),
"cameras" : []
},
{
"name" : "OrgChart - Student Success",
"uuid" : NumberLong(20),
"cameras" : []
},
{
"name" : "OrgChart - Student Life",
"uuid" : NumberLong(21),
"cameras" : []
}
],
"userid" : "user-56cb3c4c0c953470865336",
"firstviewhost" : undefined
}
2) Floorplan . The structure of the document
{
"_id" : ObjectId("589025b03422cafc09913363"),
"userid" : "user-56cb3c4c0c953470865336",
"firstviewhost" : "dean.vizsafe.com"
}
I would like to update the firstviewhost in Floorpla_backup with the value "dean.vizsafe.com" by matching the userid of both the collections.
The javascript code used is :-
db.floorplan_backup.find().forEach(function (doc1) {
var doc2 = db.floorplan.find({ userid: doc1.userid }, { firstviewhost: 1 });
if (doc2 != null) {
doc1.firstviewhost = doc2.firstviewhost;
db.floorplan_backup.save(doc1);
}
});
But is is not giving me the desired resultset . Could you let me know what is wrong with this?
doc2 is an array. Use findOne to get an object.
db.floorplan_backup.find().forEach(function (doc1) {
var doc2 = db.floorplan.findOne({ userid: doc1.userid }, { firstviewhost: 1 });
if (doc2 != null) {
doc1.firstviewhost = doc2.firstviewhost;
db.floorplan_backup.save(doc1);
}
});
find returns you a cursor, instead use findOne.
db.floorplan_backup.find().forEach(function (doc1) {
var doc2 = db.floorplan.findOne({ userid: doc1.userid }, { firstviewhost: 1 });
if (doc2 != null) {
doc1.firstviewhost = doc2.firstviewhost;
db.floorplan_backup.save(doc1);
}
});

How to query single document which contains specific value of some element in array of arrays MongoDB

I have an document that contains array of arrays i am using embedded document in MongoDb.Say i have collection name Orders looks like:-
"_id" : "HjPGrdkffg7dQPtiX",
"ListOrdersResult" : [
{
"Orders" : {
"Order" : [
{
"LatestShipDate" : "2016-01-13T18:29:59Z",
"OrderType" : "StandardOrder",
"PurchaseDate" : "2016-01-11T10:24:49Z",
"PaymentExecutionDetail" : {
"PaymentExecutionDetailItem" : {
"PaymentMethod" : "COD",
"Payment" : {
"CurrencyCode" : "INR",
"Amount" : "839.30"
}
}
},
"BuyerEmail" : "vccdbptpx2ssd74882#marketplace.amazon.in",
"AmazonOrderId" : "402-4031538-7451469",
"LastUpdateDate" : "2016-01-14T06:47:17Z",
"ShipServiceLevel" : "IN Exp Dom 2",
"NumberOfItemsShipped" : "1",
"OrderStatus" : "Shipped",
"SalesChannel" : "Amazon.in",
"ShippedByAmazonTFM" : "false",
"LatestDeliveryDate" : "2016-01-19T18:29:59Z",
"NumberOfItemsUnshipped" : "0",
"BuyerName" : "xyz",
"EarliestDeliveryDate" : "2016-01-13T18:30:00Z",
"OrderTotal" : {
"CurrencyCode" : "INR",
"Amount" : "839.30"
},
"IsPremiumOrder" : "false",
"EarliestShipDate" : "2016-01-11T18:30:00Z",
"MarketplaceId" : "A21TJRRWUN4KGVC",
"FulfillmentChannel" : "MFN",
"TFMShipmentStatus" : "Delivered",
"PaymentMethod" : "COD",
"ShippingAddress" : {
"StateOrRegion" : "HARYANA",
"City" : "GURGAON",
"Phone" : "9999999999",
"CountryCode" : "IN",
"PostalCode" : "122001",
"Name" : "Murthy",
"AddressLine1" : "House No. , J Block, Badshahpur"
},
"IsPrime" : "false",
"ShipmentServiceLevelCategory" : "Expedited"
},
{
"LatestShipDate" : "2016-01-13T18:29:59Z",
"OrderType" : "StandardOrder",
"PurchaseDate" : "2016-01-11T13:16:49Z",
"PaymentExecutionDetail" : {
"PaymentExecutionDetailItem" : {
"PaymentMethod" : "COD",
"Payment" : {
"CurrencyCode" : "INR",
"Amount" : "899.40"
}
}
},
"BuyerEmail" : "xyz#marketplace.amazon.in",
"AmazonOrderId" : "402-2142159-5087541",
"LastUpdateDate" : "2016-01-14T06:47:15Z",
"ShipServiceLevel" : "IN Exp Dom 2",
"NumberOfItemsShipped" : "1",
"OrderStatus" : "Cancel",
"SalesChannel" : "Amazon.in",
"ShippedByAmazonTFM" : "false",
"LatestDeliveryDate" : "2016-01-19T18:29:59Z",
"NumberOfItemsUnshipped" : "0",
"BuyerName" : "demo prakash",
"EarliestDeliveryDate" : "2016-01-13T18:30:00Z",
"OrderTotal" : {
"CurrencyCode" : "INR",
"Amount" : "899.40"
},
"IsPremiumOrder" : "false",
"EarliestShipDate" : "2016-01-11T18:30:00Z",
"MarketplaceId" : "A21TJEUUN4WGV",
"FulfillmentChannel" : "MFN",
"TFMShipmentStatus" : "Delivered",
"PaymentMethod" : "COD",
"ShippingAddress" : {
"StateOrRegion" : "DELHI",
"City" : "DELHI",
"Phone" : "99999999",
"CountryCode" : "IN",
"PostalCode" : "110038",
"Name" : "Demo prakash",
"AddressLine1" : "Hn 638 gali n 04 Wazirabad new delhi"
},
"IsPrime" : "false",
"ShipmentServiceLevelCategory" : "Expedited"
},
}
]
},
"CreatedBefore" : "2015-03-19T06:17:59Z"
}
],
"ResponseMetadata" : {
"RequestId" : "cf94645e-ada7-4ec6-b161-a97d07a77817"
},
"seller_user_id" : "yg4e34ccodzf3GPR2",
}
So as you can see this is the single document that contains the whole data of array i want to fetch the orders whose status is cancel from this order array.
So for that i have use :-
var orderDetails =
orders.find({"ListOrdersResult.Orders.Order":{$elemMatch:
{ OrderStatus:"Canceled"}}}).fetch();
Also i tried with:-
orders.find({"ListOrdersResult.Orders.Order.OrderStatus":'Canceled'}).fetch();
So this will return the whole document that contains status as canceled and other as well but i want only selected result from the document that contains status as pending.
So is there any way in mongoDb to query a selected value from a single document that contains nested array of arrays as object.
Or I need to staore the values into diff diff documents thats only the solution.
Any help would be appriciated please contribute
Thanks!
You can go with any meteor aggregate package. You can use match and then group the data then send it to client-side.Like :
var ordersLines = orders.aggregate([
{$unwind : "$ListOrdersResult.Orders.Order"},
{$match : { OrderStatus:"Canceled"} },
{$project : {
OrderType : '$ListOrdersResult.Orders.Order.OrderType'
....
}
}
]);
return ordersLines;
But I suggest you go with a different document.

How to create jstree based on json Data?

I am creating JsTree with json Data. the tree is created upto second level but after second the tree is not populated.
I want to recursively call the function to add leaf to it until leaf doesnt exit.
Below is my Json:
[ {
"id" : 25,
"name" : "Output",
"path" : "/",
"type" : "folder",
}, {
"id" : 26,
"name" : "Templates",
"path" : "/",
"type" : "folder",
}, {
"id" : 27,
"name" : "Temp",
"path" : "/Output/",
"type" : "folder",
}, {
"id" : 28,
"name" : "December",
"path" : "/Output/",
"type" : "folder",
}, {
"id" : 29,
"name" : "ParameterDOC",
"path" : "/Templates/DecemberTemplates/",
"type" : "Doc",
}, {
"id" : 30,
"name" : "SimpleDoc",
"path" : "/Templates/DecemberTemplates/",
"type" : "Doc",
}, {
"id" : 31,
"name" : "DecemberTemplates",
"path" : "/Templates/",
"type" : "folder",
}, {
"id" : 32,
"name" : "NovemberTemplates",
"path" : "/Templates/",
"type" : "folder",
} ]
and code is:
function createTreeForDoc(jsonData,path,id){
for(var i=0; i < jsonData.length;i++){
if(jsonData[i].path == path){
$("<li id="+jsonData[i].name+" class=\"lib\" rel="+jsonData[i].path+" data-jstree='{\"icon\":\"images/"+jsonData[i].type+"_small.png\"}' >"+jsonData[i].name+"</li>").appendTo("#maptree");
createSubTree(jsonData,jsonData[i].path+jsonData[i].name+"/",jsonData[i].name,i);
}
}
$('#rptTree').jstree({
"plugins" : ["types"],
"core" : { "check_callback" : false, "themes" : { "dots" : false }, },
});
}
function createSubTree(jsonData,path,gid,counter){
$("<ul id=\"test"+counter+"\"></ul>").appendTo("#"+gid);
for(var i=0; i < jsonData.length;i++){
if(jsonData[i].path == path ){
$("<li id="+jsonData[i].name+" class=\"lib\" rel="+jsonData[i].path+" >"+jsonData[i].name+"</li>").appendTo("#test"+counter);
}
}
}
and right now i am getting out this:
so this creates till second level third level is not created how to recursively call a function to create all other level to end.
I am not able to get what you are trying to do ,but by looking your json data you can do in the following way.Here I am using a recursive function:
function filterData(globalData,parentPath){
var result=[];
for(var i =0; i<globalData.length;i++){
if(globalData[i].path == parentPath){
result.push(data[i]);
}
}
return result;
}
function renderTree(data,parentNodeId)
{
for (var i=0; i<data.length;i++)
{
if(data[i].type == 'folder')
{
$("<li id="+data[i].name+ ">"+data[i].name+"</li>").appendTo($('#'+parentNodeId));
var childNodes=filterData(globalData,data[i].path+data[i].name+"/");
if(childNodes.length > 0)
{
$("<ul id="+data[i].path+data[i].name+"></ul>").appendTo($('#'+data[i].name));
renderTree(childNodes,data[i].path+data[i].name);
}
}
else
{
$("<li id="+data[i].name+">"+data[i].name+"</li>").appendTo($('#'+parentNodeId));
}
}
hope it will work.
You have to use a recursive function to build your tree. This function should look like:
function recursive(jsonData,parent,counter=0)
{
$("<li id="+parent.path+parent.name+" class=\"lib\" rel="+parent.path+" >"+parent.name+"</li>").appendTo("#test"+counter);
counter = 0;
for(a = 0; a<jsonData.length; a++)
{
if((parent.path+ parent.name) == jsonData[a].path)
{
$("<li id="+jsonData[a].path+jsonData[a].name+" class=\"lib\" rel="+jsonData[a].path+" data-jstree='{\"icon\":\"images/"+jsonData[i].type+"_small.png\"}' >"+jsonData[a].name+"</li>").appendTo("#maptree");
if(jsonData[a].type == "folder")
{
recursive(jsonData,jsonData[a],counter);
}
}
counter++;
}
}
This is an example, i'm notsure it works but it might be close enought for you to enhance it. :)
Good luck...

Categories