Push nested json values to array using node js - arrays

I need to show my json results into nested array format:
{
"state": [
{
"stateName": "tamilnadu"
}
],
"city": [
{
"cityName": "chennai"
}
]
}
This is my code. I'm new in node development
exports.stateId = function (req, res) {
state.find(req.body.countryId, function() {
var query = N1qlQuery.fromString('SELECT stateId,stateName FROM travel _type='state'');
myBucket.query(query, async function(err, result) {
var state=[];
await result.forEach(ele => {
var item= {
stateName:ele.stateName
}
if(ele.stateName != undefined)
state.push(item);
});
res.send({state});
});
});
};
exports.cityId = function (req, res) {
city.find(req.body.stateId, function() {
var query = N1qlQuery.fromString('SELECT cityId,cityName FROM travel where _type="city"');
myCluster.query(query, async function(err, result) {
var city=[];
await result.forEach(ele => {
var item= {
cityName:ele.cityName
}
if(ele.cityName != undefined)
city.push(item);
});
res.send({city});
});
});
};
Currently i will get results like two different array. i need to merge json results into single nested data

If you have the following data:
const data_1 =
{
"state": [
{ "stateName": "tamilnadu" }
]
};
const data_2 =
{
"city": [
{ "cityName": "chennai" } ]
};
and your desired object is:
{
"state": [
{
"stateName": "tamilnadu"
}
],
"city": [
{
"cityName": "chennai"
}
]
}
then you can use Object.assign method:
let desired = Object.assign({}, data_1, data_2);
console.log(`desired: `, desired)

Related

ReactHook adding array of an array state without duplicating the key

I am trying to add data grouping by the unit name for showing functionality
const [allData , setAllData]= useState([{'unit':'' , data:[]}])
useEffect(async () => {
await axios.get(`${BACKEND_URL}/data`).then(res => {
res.data.map(elem => {
setAllData(prev =>[...prev , { 'unit': elem.unitName, 'data': [elem.lessonName] }]);
});
});
}, []);
the result is duplicating the key for the subarray which is "unit" for my exampl:
[
{
"unit": "unit 1",
"data": [
"LO1"
]
},
{
"unit": "unit 2",
"data": [
"LO2"
]
},
{
"unit": "unit 3",
"data": [
"LO3"
]
},
{
"unit": "unit 1",
"data": [
"LO15"
]
}
]
Try like that, if find unique property unit rewrite data or push new element to array
useEffect(async () => {
await axios.get(`${BACKEND_URL}/data`).then(res => {
setAllData((prev) => {
let result = [...prev];
res.data.forEach(({ unitName: unit, lessonName }) => {
const index = result.findIndex((elem) => elem.unit === unit);
if (index >= 0) {
result[index].data = [...result[index].data, lessonName]
} else {
result.push({unit, data: [lessonName]});
}
});
return result;
});
});
}, []);

Logic App - Refer and map fields on different JSON data sources

I have two JSON data sources:
Source Data 1:
{
"result": [
{
"resource_list": "7961b907db9253045fbdf1fabf9619d4,55617907db9253045fbdf1fabf9619d2",
"project": "11216",
"project_manager": {
"value": "55617907db9253045fbdf1fabf9619d2"
}
}
]
}
Source Data 2:
{
"result": [
{
"sys_id": "7961b907db9253045fbdf1fabf9619d4",
"email": "test.user1#mysite.com"
},
{
"sys_id": "55617907db9253045fbdf1fabf9619d2",
"email": "test.user2#mysite.com"
}
]
}
I want to reference "resource_list" and "project_manager" from Source Data 1 to "sys_id" in Source Data 2 and get "email" out from Source Data 2 and then compose a final Output like below:
Output:
[
{
"__metadata":
{
"uri": "ProjectCode"
},
"externalProject": "11216",
"projectCodeAssignment":
[
{
"__metadata":
{
"uri": "projectCodeAssignment"
},
"externalProjectAssignee": "test.user1#mysite.com"
},
{
"__metadata":
{
"uri": "projectCodeAssignment"
},
"externalProjectAssignee": "test.user2#mysite.com"
}
]
}
]
Is this possible to get this done entirely in Logic App without using Function App or anything to perform it rather.
I write a js script for you. For a quick demo, I omitted some data related to __metadata, seems that is some hard code, not so important here. Try Logic below:
Code in JS code action:
var body = workflowContext.trigger.outputs.body
var data1 = body.data1;
var data2 = body.data2;
var result = [];
data1.result.forEach(item =>{
var resultItem = {};
resultItem.externalProject = item.project;
resultItem.projectCodeAssignment =[];
var resourceIds = item.resource_list.split(',');
resourceIds.forEach(id =>{
var user = data2.result.find( ({ sys_id }) => sys_id === id );
resultItem.projectCodeAssignment.push({"externalProjectAssignee": user.email})
});
result.push(resultItem);
})
return result;
Request Body(your 2 data set are named as data1 and data2 here ):
{
"data1": {
"result": [{
"resource_list": "7961b907db9253045fbdf1fabf9619d4,55617907db9253045fbdf1fabf9619d2",
"project": "11216",
"project_manager": {
"value": "55617907db9253045fbdf1fabf9619d2"
}
}
]
},
"data2": {
"result": [{
"sys_id": "7961b907db9253045fbdf1fabf9619d4",
"email": "test.user1#mysite.com"
}, {
"sys_id": "55617907db9253045fbdf1fabf9619d2",
"email": "test.user2#mysite.com"
}
]
}
}
Result:

Response duplicated but the count shows as 1

Using Dynamoose ORM with Serverless. I have a scenario where I'm finding user information based on recommendation.
The response is as follows
{
"data": {
"results": [
{
"specialTip": "Hello World",
"recommendation": "Huli ka!",
"poi": {
"uuid": "poi_555",
"name": "Bukit Panjang",
"images": [
{
"url": "facebook.com",
"libraryUuid": "2222",
"uuid": "9999"
}
]
},
"uuid": "i_8253578c-600d-4dfd-bd40-ce5b9bb89067",
"headline": "Awesome",
"dataset": "attractions",
"insiderUUID": "i_c932e85b-0aee-4462-b930-962f555b64bd",
"insiderInfo": [
{
"gender": "m",
"funFacts": [
{
"type": "knock knock!",
"answer": "Who's there?"
}
],
"profileImage": "newImage.jpg",
"shortDescription": "Samething",
"fullDescription": "Whatever Description",
"interests": [
"HELLO",
"WORLD"
],
"tribes": [
"HELLO",
"WORLD"
],
"uuid": "i_c932e85b-0aee-4462-b930-962f555b64bd",
"personalities": [
"HELLO",
"WORLD"
],
"travelledCities": [
"HELLO",
"WORLD"
]
}
]
},
{
"specialTip": "Hello World",
"recommendation": "Huli ka!",
"poi": {
"uuid": "poi_555",
"name": "Bukit Panjang",
"images": [
{
"url": "facebook.com",
"libraryUuid": "2222",
"uuid": "9999"
}
]
},
"uuid": "i_8253578c-600d-4dfd-bd40-ce5b9bb89067",
"headline": "Awesome",
"dataset": "attractions",
"insiderUUID": "i_c932e85b-0aee-4462-b930-962f555b64bd",
"insiderInfo": [
{
"gender": "m",
"funFacts": [
{
"type": "knock knock!",
"answer": "Who's there?"
}
],
"profileImage": "newImage.jpg",
"shortDescription": "Samething",
"fullDescription": "Whatever Description",
"interests": [
"HELLO",
"WORLD"
],
"tribes": [
"HELLO",
"WORLD"
],
"uuid": "i_c932e85b-0aee-4462-b930-962f555b64bd",
"personalities": [
"HELLO",
"WORLD"
],
"travelledCities": [
"HELLO",
"WORLD"
]
}
]
}
],
"count": 1
},
"statusCode": 200
}
Not sure where I'm going wrong as the items in the response seems to be duplicated but the count is 1.
Here is the code
module.exports.index = (_event, _context, callback) => {
Recommendation.scan().exec((_err, recommendations) => {
if (recommendations.count == 0) {
return;
}
let results = [];
recommendations.forEach((recommendation) => {
Insider.query({uuid: recommendation.insiderUUID}).exec((_err, insider) => {
if (insider.count == 0) {
return;
}
recommendation.insiderInfo = insider;
results.push(recommendation);
});
});
const response = {
data: {
results: results,
count: results.count
},
statusCode: 200
};
callback(null, response);
});
};
EDIT: My previous code ignored the fact that your "Insider" query is asynchronous. This new code handles that and matches your edit.
const async = require('async'); // install async with 'npm install --save async'
[...]
module.exports.index = (_event, _context, callback) => {
Recommendation.scan().exec((_err, recommendations) => {
if (_err) {
console.log(_err);
return callback(_err);
}
if (recommendations.count == 0) {
const response = {
data: {
results: [],
count: 0
},
statusCode: 200
};
return callback(null, response);
}
let results = [];
async.each(recommendations, (recommendation, cb) => { // We need to handle each recommendation asynchronously...
Insider.query({uuid: recommendation.insiderUUID}).exec((_err, insider) => { // because this is asynchronous
if (_err) {
console.log(_err);
return callback(_err);
}
if (insider.count == 0) {
return cb(null);
}
recommendation.insiderInfo = insider;
results.push(recommendation);
return cb(null);
});
}, (err) => { // Once all items are handled, this is called
if (err) {
console.log(err);
return callback(err);
}
const response = { // We prepare our response
data: {
results: results, // Results may be in a different order than in the initial `recommendations` array
count: results.count
},
statusCode: 200
};
callback(null, response); // We call our main callback only once
});
});
};
Initial (partly incorrect) answer, for reference.
You are pushing the result of your mapping into the object that you are currently mapping and callback is called more than once here. That's a pretty good amount of unexpected behavior material.
Try the following:
let results = [];
recommendations.forEach((recommendation) => {
Insider.query({uuid: recommendation.insiderUUID}).exec((_err, insider) => {
if (insider.count == 0) {
return;
}
recommendation.insiderInfo = insider;
results.push(recommendation);
});
});
let response = {
data: {
results: results,
count: results.count
},
statusCode: 200
};
callback(null, response);

AngularJS: mocking the service in a controller using Jasmine

Could you please help me to write down the Jasmine(2.0) test code for mock of the service in a Controller as below.
readJsonFactory.js
angular.module('myAssignmentTaskApp')
.factory('readJsonFactory', function ($http) {
var userExists = false;
var responseData = [];
return $http.get('../json/AutoTestDB1.json').then(function (response) {
for (var i=0; i<response.data.StatusTable.length; i++){
responseData.push(response.data.StatusTable[i].RunId);
}
return response;
}).catch(function (error) {
//
})
});
The Controller file readjson.js is as below.
angular.module('myAssignmentTaskApp')
.controller('ReadjsonctrlCtrl', function ($scope,readJsonFactory,$location) {
var testCaseNameFromReadJsonFactory = [];
readJsonFactory.then(function (response) {
for (`var i=0;i<response.data.StatusTable.length;i++`){
testCaseNameFromReadJsonFactory.push(response.data.StatusTable[i].TestScenario);
}
}
})
AutoTestDB1.json
{
"StatusTable": [
{
"RunId": "bah_regression_alternateFlights",
"TestScenario": "BAH - Change Default Search Options",
"Area": "Yes",
"TestCases": [
{
"TestID": "",
"TestName": "VerifyCarDepotPageIsDisplayed_Test",
"Status": [
{
"Release": " R301",
"Runner": "yes",
"Status": "Passed",
"details": [
{
"ResponseTime": "1m 26s 702ms",
"Status": "Passed",
"RecordData": 1511519114413
}
]
}
]
}
]
}
]
}
Please post an apporopriate spac.js file.
Thanks in advance.
You do use the following to mock your service
beforeEach(function() {
angular.mock.module('myAssignmentTaskApp', ($provide) => {
const mockReadJsonFactory = {
};
$provide.constant('readJsonFactory', mockReadJsonFactory);
});
});

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