combine two array as key value pair - arrays

I have two array as follows
var field_array=["booktitle","bookid","bookauthor"];
var data_array=["testtitle","testid","testauthor"];
I want to combine these two array and covert it to the following format
var data={
"booktitle":"testtitle",
"bookid":"testid",
"bookauthor":"testauthor"
}
I want to insert this data to database using nodejs
var lastquery= connection.query('INSERT INTO book_tbl SET ?',data, function (error, results, fields) {
if (error) {
res.redirect('/list');
}else{
res.redirect('/list');
}
});
Please help me to solve this.

var field_array = ["booktitle", "bookid", "bookauthor"];
var data_array = ["testtitle", "testid", "testauthor"];
var finalObj = {};
field_array.forEach(function (eachItem, i) {
finalObj[eachItem] = data_array[i];
});
console.log(finalObj); //finalObj contains ur data

You also can use reduce() in a similar way:
var field_array=["booktitle","bookid","bookauthor"];
var data_array=["testtitle","testid","testauthor"];
var result = field_array.reduce((acc, item, i) => {
acc[item] = data_array[i];
return acc;
}, {});
console.log(result);

Here I explaned my code line by line..Hope it will help
var field_array = ["booktitle", "bookid", "bookauthor"];
var data_array = ["testtitle", "testid", "testauthor"];
//Convert above two array into JSON Obj
var jsondata = {};
field_array.forEach(function (eachItem, i) {
jsondata[eachItem] = data_array[i];
});
//End
//Store Jsondata into an array according to Database column structure
var values = [];
for (var i = 0; i < jsondata.length; i++)
values.push([jsondata[i].booktitle, jsondata[i].bookid, jsondata[i].bookauthor]);
//END
//Bulk insert using nested array [ [a,b],[c,d] ] will be flattened to (a,b),(c,d)
connection.query('INSERT INTO book_tbl (booktitle, bookid, bookauthor) VALUES ?', [values], function(err, result) {
if (err) {
res.send('Error');
}
else {
res.send('Success');
}
//END

Related

trying to convetr json array to multiple json objects in nodejs

trying to convetr json array to multiple json objects in nodejs looking for help here is my code have tried loops to achieve that but failed just want to send the data as multiple objects not array
router.get('/frontpage-mobile', function (req, res, next) {
qryFilter = { "Product_Group": 'SIMPLE' };
// if we have a cart, pass it - otherwise, pass an empty object
var successMsg = req.flash('success')[0];
var errorMsg = req.flash('error')[0];
Product.find(qryFilter, function (err, product) {
// console.log("Product: " + JSON.stringify(product));
var pro=JSON.stringify(product)
if (err || product === 'undefined' || product == null) {
// replace with err handling
var errorMsg = req.flash('error', 'unable to find product');
res.send(errorMsg);
}
if (!product) {
req.flash('error', 'Product is not found.');
res.send('error', 'Product is not found.');
}
for(i=0;i<pro.length;i++)
res.send(pro[i]);
});
});
// Dummy Mongodb Result Array
var db_result = [{_id:1,name:"Cake_1"},{_id:2,name:"Cake_2"},{_id:3,name:"Cake_3"}]
// define data variable
var data = { total : 0, dataObj : {} } // default total = 0, = {}
var dataObj = {}
// convert array to obj
// { key1 : obj1, key2 : obj2, key3 : obj3, ... }
for(var i=0; i < db_result.length;i++){
let key = "key"+i;
dataObj[key] = db_result[i];
}
// assign data to variable
data.total = db_result.length;
data.dataObj = dataObj
// rend back to client
res.send(data);
// Result
{
"total":3,
"dataObj":{
"key0":{"_id":1,"name":"Cake_1"},
"key1":{"_id":2,"name":"Cake_2"},
"key2":{"_id":3,"name":"Cake_3"}
}
}

How to change [] with {} in my array object

I retrieve this data from an API
{"city":"New York","type":["0","1","9"]}
I need to convert in this way:
{"type":{0:true,1:true,9:true},...}
I try with angular foreach in this way
var tmparr = [];
angular.forEach( $scope.path.type, function (value, key) {
tmparr.push(value + ":true")
});
$scope.checkfilters.type = tmparr
but in this way i have this result and it's not what i need
{"business_type":["0:true","1:true","9:true"]}
I don't know how to replace the [] with {} in my array
If I try to set var tmparr = {} I have undefined error in push function
Use bracket syntax
var tmparr = {};
angular.forEach( $scope.path.type, function (value, key) {
tmparr[value] = true;
});
$scope.checkfilters.type = tmparr;
You can loop through the type and then copy the values and assign it to true.
var original = {"city":"New York","type":["0","1","9"]};
var copy = {};
for(var i in original.type){
copy[original.type[i]] = true;
}
console.log(copy);
You can also use reduce with an object accumulator:
var data = {"city":"New York","type":["0","1","9"]}
const result = data.type.reduce((r,c) => (r[c] = true, r), {})
console.log(result)

Angular, http return double int array

When I return a double/two dimensional array from my MVC project in my Angular app it only returns a single array. How do I return a double array from my MVC controller to my Angular app?
function getStatusView() {
dataFactory.getStatusView()
.then(function (response) {
$scope.statusview = response.data.StatusViewList;
$scope.modelList = response.data.ModelList;
$scope.modelClustersList = response.data.ModelCLustersList;
$scope.turbineNumberDistinct = response.data.TurbineNumbersDistinct;
$scope.alarmArray = response.data.statusArray;
}, function (error) {
$scope.status = 'Unable to load customer data: ' + error.message;
});
}
[HttpGet]
public JsonResult GetStatusView()
{
model.statusArray = new int[model.ModelList.Count, model.StatusViewList.Count];
var statuslinesWithAlarm = statusView.Where(p => p.AlarmLevel> 0).ToList();
foreach (var statuslineWithAlarm in statuslinesWithAlarm)
{
var turbineIndex = model.StatusViewList.Select(p => p.TurbineNumber).ToList().IndexOf(statuslineWithAlarm.TurbineNumber);
var modelIndex = model.ModelList.IndexOf(statuslineWithAlarm.ModelName);
model.statusArray[modelIndex,turbineIndex] = 1;
}
return Json(model, JsonRequestBehavior.AllowGet);
}
Javascript does not know about this kind of 2D arrays, so you will not get the expected result after deserialization. Instead declare your model as an array of arrays. Something like:
var model = new int[][] { new [] { ... }, new [] { ... }, new [] { ... } }
Json.Net overcomes this issue by correctly serializing multiple dimension arrays into arrays of arrays:
JsonConvert.SerializeObject(model);

make value of one( key value pair )to be key of another in angular js

i am having a json response from which i wanted to create new json object
response = [
{Detail:"Reuters ID",keyName:"Reuters_ID"},
{Detail:"Parity One",keyName:"parity_one"},
{Detail:"Parity level",keyName:"parity_level"}
];
i wanted to achieve this after manipulating keys and value pair
lang_Arr =[
{Reuters_ID:"Reuters ID"},
{parity_one:"Parity One"},
{parity_level:"Parity level"}
];
i have tried doing it in two ways
1) in this getting error as unexpected tokken (.)
var Lang_arr =[];
angular.forEach(response, function(value, key) {
Lang_arr.push({value.keyName:value.Detail});
});
2) here getting unxepected token [
var Lang_arr =[];
angular.forEach(response, function(value, key) {
Lang_arr.push({value['keyName']:value['Detail']});
});
i have tried assigning the values seperatly too but it doesn't work there also
var Lang_arr=[];
var k ='';
var v ='';
var i = 1;
angular.forEach(response, function(value, key) {
k ='';
v ='';
i = 1;
angular.forEach(value,function(val,key){
if(i == 1 )
k = val;
if(i == 2)
v = val;
if(!empty(k) && !empty(v))
Lang_arr.push({k:v})
i++;
});
});
You can use javascript map function to map the objects to array
var response = [
{Detail:"Reuters ID",keyName:"Reuters_ID"},
{Detail:"Parity One",keyName:"parity_one"},
{Detail:"Parity level",keyName:"parity_level"}
];
var lang_Arr =[];
lang_Arr = response.map(function(o){
var obj = {};
obj[o.Detail] = o.keyName;
return obj;
})
console.log(lang_Arr)
With Angular forEach also you can achieve this functionality
var response = [
{Detail:"Reuters ID",keyName:"Reuters_ID"},
{Detail:"Parity One",keyName:"parity_one"},
{Detail:"Parity level",keyName:"parity_level"}
];
var modifiedArray = [];
angular.forEach(response, function(val, key) {
var res = {};
res[val.keyName] = val.Detail;
this.push(res);
}, modifiedArray);
console.log(modifiedArray)
Working Example in Fiddle
You have to assign it in the http call that gets the response
$htpp.get(....).then(function(response){
lang_arr = [];
response.forEach(function(obj){
var item = {obj.keyName : obj.detail};
lang_arr.push(item);
}

AngularJS promise through tow loops

Have some trouble with Angular promise between two loops... First loop walk through an array of value, and for each value, make a PouchDB Query to retrieve some datas. Finally, would like to return to controller a JSON Object that would look like :
{
items: [
{
"attribute": "some value"
},
{
"attribute": "some other value"
},
...
],
"a_total": "some_total",
"another_total": "some_other_total"
}
In this object, "items"
Basically, put the code in a function that looks like :
var _stockByAreas = function(){
var deferred = $q.defer();
var data = {}; // Final datas to return to controller
// Get first array to loop into
var storageAreas = storageAreaService.storageAreaList();
var areas = []; // All of area
// Walk across array
angular.forEach(storageAreas, function(zone){
var area = {}; // First object to return
area.id = zone.id;
area.libelle = zone.libelle;
// Then make a PouchDB query to get all datas that involved
MyKitchenDB.query(function(doc, emit){
emit(doc.storage);
}, { key: area.id, include_docs: true }).then(function (result) {
area.sRef = "tabsController.addTo({id: '" + area.id + "'})";
area.nbProduct = 0;
area.totalQuantity = 0;
area.totalValue = 0;
// ... process result
if(result.rows.length > 0){
// Some results, so... let's go
area.sRef = "tabsController.outFrom({id: '" + area.id + "'})";
var rows = result.rows;
// Counter initialization
var total = 0;
var value = 0;
angular.forEach(rows, function(row){
total++;
var stocks = row.doc.stock;
angular.forEach(stocks, function(stock){
var nearOutOfDate = 0;
var nearStockLimit = 0;
quantity += stock.quantity;
value += stock.quantity * stock.price;
// Evalue la date de péremption
var peremptionDate = moment(stock.until);
var currentDate = moment();
if(currentDate.diff(peremptionDate, 'days') <= 1){
nearOutDate += 1;
}
});
area.nbProduct = total;
area.qteTotale = quantity;
area.valeur = value;
if(quantite == 1){
nearLimitOfStock += 1;
}
areas.push(area); // Add result to main array
});
}
}).catch(function (err) {
// Traite les erreurs éventuelles sur la requête
});
/**
* Hey Buddy... what i have to do here ?
**/
data.items = areas;
data.nearLimitOfStock = nearLimitOfStock;
data.nearOutOfDate = nearOutOfDate;
});
deferred.resolve(data);
return deferred.promise;
}
... But, console returns that "areas" is not defined, and other value too...
I think i don't really understand how promises runs...
Someone is abble to explain why i can't get the result that i expect in my case ?
Thx
Your code is too long, I just give you the approach.
Use $q.all() to ensure all your queries are completed. And use deferred.resolve(data) whenever your data for each query is arrived.
var _stockByAreas = function() {
var query = function(zone) {
var queryDef = $q.defer();
// timeout is for query and response simulations
setTimeout(function() {
// ...
queryDef.resolve( {data: 'MeTe-30'} );
}, 1000);
return queryDef.promise;
}
var promises = [];
angular.forEach(storageAreas, function(zone) {
// ...
promises.push( query(zone) );
});
return $q.all(promises);
}
_stockByAreas().then(function(res) {
// res[0] resolved data by query function for storageAreas[0]
// res[1] resolved data by query function for storageAreas[1]
// ...
});

Resources