Get data from complex Json structure using NodeJs - arrays

json Structure:
{
"id" : "1",
"Data" : [
{
"name" : "abc",
},
{
"name" : "option1",
"position" : [
{
"name" : "option1",
"status" : [
{
"code" : "0",
"value" : "OFF"
},
{
"code" : "1",
"value" : "ON"
}
]
}]
} ]
}
Here,I want to get the data from above complex Json structure.How to do that,
Have tried below code but giving error like;
error: uncaughtException: Cannot read property 'status' of undefined
function myfunc(req,res){
var collectionname = db.collection("col1");
collectionname.find({}).each(function(err, doc) {
if(doc != null)
{
var fdata = [];
for(var i =0;i<doc.Data.length;i++){
fdata.push(doc.Data[i].position.status);
}
console.log("fdata............",fdata);
}
});
}
Please help with the same.

You can use foreach for prevent length undefined.
function myfunc(req,res)
{
let collectionname = db.collection("col1");
collectionname.find({}).each(function(err, doc)
{
if(doc != null)
{
let fdata = [];
for(let i in doc.Data)
{
for(let j in doc.Data[i].position)
{
fdata.push(doc.Data[i].position[j].status);
}
}
console.log("fdata............", fdata);
}
});
}
#MikaelLennholm have right, for(let i in doc.Data) works but not recommanded, be careful not to use it in prototyped or object-built arrays.
EDIT:
function myfunc(req,res)
{
db.collection('col1').find({}).each(function(err, doc)
{
if(err)
{
console.log('[INFOS] Request fail, more details:\n', err);
}
else if(doc)
{
let fdata = [];
if(doc.Data && doc.Data.length)
{
for(let i = doc.Data.length-1; i >= 0; i--)
{
if(doc.Data[i].position && doc.Data[i].position.length)
{
for(let j = doc.Data[i].position.length-1; j >= 0; j--)
{
if(doc.Data[i].position[j].status)
{
fdata = fdata.concat(doc.Data[i].position[j].status);
}
}
}
}
}
console.log("[INFOS] Datas:\n", fdata);
}
});
}

im a newbie at nodejs, hope this's correctly
//I assume this is a object or you can convert from string to object
var data = {
"id": "1",
"Data": [
{
"name": "option1",
"position": [
{
"name": "option1",
"status": [
{
"code": "0",
"value": "OFF"
},
{
"code": "1",
"value": "ON"
}
]
}]
}]
}
var statusArr = data.Data[0].position[0].status;
console.log(...statusArr);
Result: { code: '0', value: 'OFF' } { code: '1', value: 'ON' }

Parse through position array as well
function myfunc(req,res){
var collectionname = db.collection("col1");
collectionname.find({}).each(function(err, doc) {
if(doc != null)
{
var fdata = [];
for(var i =0;i<doc.Data.length;i++){
for(var j =0;j<doc.Data[i].position.length;j++){
fdata.push(doc.Data[i].position[j].status);
}
}
console.log("fdata............",fdata);
}
});
}

Related

How to delete all sub array

In my MongoDB database, I have a collection 'produits' with documents like this
{
"_id": {
"$oid": "6048e97b4a5f000096007505"
},
"modeles": [
{
"id": "OppoA3",
"pieces": [
{
"id": "OppoA3avn"
},
{
"id": "OppoA3bat"
}]
]
},
{
"id": "OppoA1",
"pieces": [
{
"id": "OppoA1avn",
},
{
"id": "OppoA1batt",
}
]
}
]
}
How can I delete all modeles.pieces from all my documents.
I managed to delete with a filter on modeles.id but with that code but not on all the collection
db.produits.update(
{marque_id:'OPPO', 'modeles.id':'RENOZ'},
{$set:
{
'modeles.$.pieces': []
}
}
, { multi : true }
)
I would like all documents like this finally
{
"_id": {
"$oid": "6048e97b4a5f000096007505"
},
"modeles": [
{
"id": "OppoA3",
"pieces": []
},
{
"id": "OppoA1",
"pieces": []
}
]
}
Thank you for your help.
I have done a javascript loop like this, but i think it's not best practice
async removePieces(){
var doc
try {
doc = await produitModel.find()
for (var produit of doc) {
for (var modele of produit.modeles) {
const filter = {'marque_id': produit.marque_id, 'modeles.id': modele.id}
const set = {
$set: {
'modeles.$.pieces': []
}
}
await db.collection('produits').updateOne(filter, set)
}
}
console.log('removePieces() ==> Terminé')
} catch(err) {
console.log(err)
}
}
db.produits.update({
modeles: {//This is because your second document will create failure otherwise
$exists: true
}
},
{
$set: {
"modeles.$.pieces": []
}
},
{
multi: true
})

how to add 2 element in nested array from one root element using JOLT specification?

Input:
{
"k1": "v1",
"k2": "v2",
"event": "SUMMARY"
}
Expected output:
{
"k1": "v1",
"k2": "v2",
"event": "SUMMARY",
"arr": [
{
"k1": "v1",
"key": "first"
},
{
"k2": "v2",
"key": "second"
},
{
"summary1": "s1",
"key": "SUMMARY"
},
{
"summary1": "s2",
"key": "SUMMARY"
}
]
}
For each 'k1' and 'k2', respective array element should be added as
{
"k2": "v2",
"key": "second"
}
For when event = "SUMMARY", respective 2 elements should be added as
{
"summary1": "s1",
"key": "SUMMARY"
},
{
"summary2": "s2",
"key": "SUMMARY"
}
Please help with JOLT specification
Since you gave input and output based on that i written
one function in javascript.
{
"k1": "v1",
"k2": "v2",
"event": "SUMMARY"
}
Well that function will work only for above input
and also you have to mention that whether u want output in which language...
//Input
var obj = {
"k1": "v1",
"k2": "v2",
"event": "SUMMARY"
}
//funciton calling
obj["arr"] = checkThis(obj);
//output
console.log(obj)
function checkThis(obj) {
var arr = [];
Object.keys(obj)
.forEach(function eachKey(key) {
if (key == "k1") {
var tempObj = {}
tempObj["k1"] = obj[key];
tempObj["key"] = "first";
arr.push(tempObj)
} else if (key == "k2") {
var tempObj = {}
tempObj["k2"] = obj[key];
tempObj["key"] = "second";
arr.push(tempObj)
} else if (key == "event") {
var tempObj1 = {}
var tempObj2 = {}
tempObj1["summary1"] = "s1";
tempObj1["key"] = obj[key];
tempObj2["summary1"] = "s2";
tempObj2["key"] = obj[key];
arr.push(tempObj1)
arr.push(tempObj2)
}
});
return arr;
}

Protractor test not executing

I have a protractor test. I want to provide some data for a test so i can generate tests automatically.
My function is as below. The problem is that i can console log something after the opening of describe. But this is'nt the case after the it function.
The code:
bigTestFunction = function(testElements) {
testElements = JSON.parse(testElements);
for (i = 0; i < testElements.length; i++) {
var title = testElements[i].title;
var shouldText = testElements[i].should
var url = testElements[i].url;
var actions = testElements[i].action;
describe(title, function() {
it(shouldText, function() {
goToUrl(url);
for (x = 0; x < actions.length; x++) {
var action = actions[x].action;
var value = actions[x].value;
var element = actions[x].element;
var notEmpty = actions[x].notEmpty;
var nested = actions[x].nested;
if (action === 'sendKeys') {
sendKey(element, value);
}
if (action === 'click') {
click(element, notEmpty);
if (nested) {
for (x = 0; x < nested.length; x++) {
if (nested[x]['action'] === 'sendKeys') {
sendKey(nested[x]['element'], nested[x]['value']);
}
if (nested[x]['action'] === 'click') {
click(nested[x]['element'], nested[x]['notEmpty']);
}
}
}
}
}
});
});
}
}
testElements = JSON.parse(testElements);
the json:
[
{
"id": 1,
"title": "Small test one",
"should": "should start training",
"url": "https://ledmagazine.nl/home",
"actions": [
{
"id": 1,
"test_id": 1,
"element": "/html/body/div[1]/div/div/header/div/div[2]/div[2]/div/div/div/div/nav/section/ul/li[3]/a",
"action": "click",
"status": "notEmpty",
"value": "/html/body/div[1]/div/div/div[2]/div/div/div[1]/div/section",
"nested": {
"id": 1,
"action_id": 1,
"action": "sendKeys",
"element": "//*[#id=\"mce-EMAIL\"]",
"value": "dennisageffen#hotmail.com",
"created_at": null,
"updated_at": null
}
}
]
}
]
I think i'm really close but the function stops after 'describe(title, function() {...'
Propably you are missing beforeEach(function() {...} to get data.

Parse Objects and Arrays in Json data in AngularJs

I am trying to build an array of objects using the data I get from backend service using angularjs. Here is how I get the data
"mylist": [
{
"name": "Test1",
"moreInfo": {
"moreInfoText": "More test",
},
"companyInfo": {
"companyNameInfo": "ABC",
"url": "http://www.google.com",
}
},
{
"name": "Test2",
"moreInfo": {
"moreInfoText": "More test2",
},
"companyInfo": {
"companyNameInfo": "ABC2",
"url": "http://www.yahoo.com",
}
},
]
I want to parse it so I can combine it all in one array of objects like
[{"name": "Test1", "moreInfoText": "More test","companyNameInfo": "ABC", "url": "http://www.google.com"},{ "name": "Test2", "moreInfoText": "More test2","companyNameInfo": "ABC2", "url": ""}]
Try this:
var flatten = function(object) {
var newObj = {};
for (var key in object) {
var item = object[key];
if (typeof item !== 'object') {
newObj[key] = item;
}
else {
var flattened = flatten(item);
for (var k in flattened) {
newObj[k] = flattened[k];
}
}
}
return newObj;
};
var newList = [];
myList.forEach(function(object) {
newList.push(flatten(object);
});
console.log(newList) //this should be what you want

update item of array of array in mongodb

I want to push an item to the array of items (root document > categories > subcategories > items)
I am using NodeJS with MongoDB npm package
My document structure should be like the following
{
"_id": "572a77641b24ed3404f43690"
"categories": [
{
"id": "572bbac072d7ee3026a69467"
"Name": "Foods",
"subcategories": [
{
"id": "572a777c1b24ed3404f43691",
"Name": "Pizza"
"items": [
{
"id": "572ba1666ca263303121acd4"
"Name": "4 Seasons",
"Price": "6.0"
}
]
}
]
}
]
}
My current code is
app.post("/item/:subcatid", function(req, res) {
var subId = req.params.subcatid;
var item = req.body;
item.id = new ObjectId();
items.update({ "categories.subcategories.id": ObjectId(subId) }, { $push: { "categories.0.subcategories.$.items": item } }, function(err, result) {
res.send(result);
});
});
What can I do ?
Just found a solution, not clean one though but works properly !
app.post("/item/:subcatid", function(req, res) {
var subId = req.params.subcatid;
var item = req.body;
item.id = new ObjectId();
items.findOne({ "categories.subcategories.id": ObjectId(subId) }, { "categories.subcategories.$": 1 }, function(err, doc) {
for (var i = 0; i < doc.categories[0].subcategories.length; i++) {
var elem = doc.categories[0].subcategories[i];
if (elem.id == subId) {
items.update({ "categories.subcategories.id": ObjectId(subId) }, { $push: { ["categories." + i + ".subcategories.$.items"]: item } }, function(err, result) {
res.send(result);
});
break;
}
}
});
});

Resources