AngularJS : How can i convert .properties file in to json object - angularjs

I got a requirement to convert .properties file to JSON object using angular js.
I have no clue how to achive this, i searched in net but did not found the solution. Could you please help me with this.
.properties file contains
a.b.10=M
a.b.11=M50
a.b.12=M508
Output should be
{"a":{"b":{"10":"M","11":"M50","12":"M508"}}}

Try this
var str1 = "a.b.12=M508";
var str2 = "a.b.10=M";
var str3 = "a.b.11=M50";
var result = {};
function createObject(str) {
str.split('.').reduce((obj, key) => {
if (!obj[key] && !key.includes('='))
obj[key] = {};
else if (key.includes('=')) {
var keys = key.split('=');
obj[keys[0]] = keys[1];
}
return obj[key];
}, result);
return result;
}
createObject(str1);
createObject(str2);
createObject(str3);
console.log(result);

Related

combine two array as key value pair

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

Trying to copy specific file from specific folder in Google Drive

I'm trying to search for a specific file File1 in a specific folder (named through another variable).
Once I have identified the file, I want to make a copy of the file.
This is what I came up with, with the help of previous posts and many google searches but nothing happens.
var folderName = ConsultName;
var files = DriveApp.getFoldersByName(folderName).next().getFiles();
files.hasNext() && files == "File1" && files.next().makeCopy();
I've tried without the files == "File1" and the makeCopy() function will end up copying whatever file is next.
I've been trying to figure this out for several days, but haven't had any luck.
Any help would be helpful. Thanks!
I use these functions in several ways for loading and saving data in other scripts. If some arguments are omitted defaults are provided automatically. I believe you can use these building blocks to conjure up a copy solution for yourself
function loadFile(filename,folderID)
{
var filename = (typeof(filename) !== 'undefined')? filename : DefaultFileName;
var folderID = (typeof(folderID) !== 'undefined')? folderID : DataFolderID;
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var s = '';
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
s = fi.getBlob().getDataAsString();
}
}
return s;
}
function saveFile(datstr,filename,append)
{
var append = (typeof(append) !== 'undefined')? append : false;
var filename = (typeof(filename) !== 'undefined')? filename : DefaultFileName;
var datstr = (typeof(datstr) !== 'undefined')? datstr : '';
var folderID = (typeof(folderID) !== 'undefined')? folderID : DataFolderID;
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var targetFound = false;
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
if(append)
{
datstr = fi.getBlob().getDataAsString() + datstr;
}
targetFound = true;
fi.setContent(datstr);
}
}
if(!targetFound)
{
var create = fldr.createFile(filename, datstr);
if(create)
{
targetFound = true;
}
}
return targetFound;
}

How do you make JS think that a string is JSON?

how to convert in json object?
I also tried the following.
$scope.getEval = function (str) {
return eval(str);
};
try {
s = $scope.getEval("\nexports = { emptyFunction: function () { \n exit(); }, getUserName: function () { if (!variable.global_name) { exit(changeFlowAndStep('get_user_name', 0, {global_first_time_done: false}, true)); } else { exit({variable:{global_first_time_done: true}}); } }}")
for (var i in s) {
s[i] = s[i].toString();
}
$scope.s = s;
console.log($scope.s)
} catch (e) {
console.log(e);
}
If you have a javascript object, it is easy to generate a JSON string with JSON.stringify() and if you have a JSON string, it is easy to generate a javascript object with JSON.parse()
// going from JSON to JS object...
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
console.log(obj);
console.log(obj.count);
// from JS object to JSON string...
var str = JSON.stringify(obj);
console.log(str);
from:
Parse JSON in JavaScript?
Convert JS object to JSON string
Your use of eval works, as you can see when you call console.dir($scope.s);
It is possible to use json = JSON.stringify(obj); and obj = JSON.parse(json);. However it appears JSON.stringify ignores object fields with a function as a value. That is your string is not a useful json string.

How to check string in json array

console.log($scope.filteredOffers);hi to all want to check string in json like that string coming form params now want to check in whole json and display only data which is related to that . Kindly check my code .. in other words want to display data according to the params which is coming form url (which is coming ).
.controller('mixCtrl', function($scope,$http,$stateParams) {
$http.get("http://tools.vcommission.com/api/coupons.php?apikey=e159f64e3dd49fddc3bb21dcda70f10c6670ea91aac30c7cb1d4ed37b20c45b8").then(function (response) {
$scope.myData = response.data;
$scope.offerName = ''; //set initially
$scope.selectedIndex = -1;
$scope.filteredOffers = [];
// $scope.link1 = [];
$scope.da = $stateParams.offer_name;
var a = $scope.da;
console.log(a);
$scope.filteredOffers = $scope.myData.filter(function(a) {
for (var i=0;i<$scope.myData.length;i++)
{
$link =$scope.myData[i].offer_name;
if (a==$link)
{
return a ;
console.log(a );
}
//console.log(a );
}
// return offer.offer_name == $scope.da;
console.log($scope.da);
});
});
/*
$scope.showData = function(offer_name, index) {
$scope.offerName = offer_name;
$scope.filteredOffers = $scope.myData.filter(function(offer) {
return offer.offer_name == $scope.offerName;
});
$scope.selectedIndex = index;
}*/
$scope.dealopen = function(a){
for (var i=0;i<$scope.myData.length;i++)
{
//console.log($scope.data[i].name);
$link=$scope.data[i].name;
console.log($link);
if ($link==$a)
{
$window.open($link,"_self","location=yes");
//console.log($a);
}
}
}
})
Html
<div ng-repeat="offer in filteredOffers">
<div class="couponCode">{{offer.coupon_code}}</div>
<div class="couponTitle">{{offer.coupon_title}}</div>
<div class="couponDescription">{{offer.coupon_Description}}</div>
</div>
You are use the Array.filter() function wrongly!
Before :
$scope.filteredOffers = $scope.myData.filter(function(a) {
for (var i=0;i<$scope.myData.length;i++)
{
$link =$scope.myData[i].offer_name;
if (a==$link)
{
return a ;
console.log(a );
}
//console.log(a );
}
// return offer.offer_name == $scope.da;
console.log($scope.da);
});
After (According to correct syntax) :
$scope.filteredOffers = $scope.myData.filter(function(a) {
if (check condition)
{
return true ;// when true is returned the json held in a gets pushed into the filteredOffers array
}
else{
return false;//when false is returned, the json held in 'a' is ignored and not pushed into the filteredOffers array
}
});
Array.filter's Doc Link
But there is something wrong with the logic that you have used. If you can tell me exactly what you are trying to do, I might be able to help you out.
If you are processing json and arrays frequently in your application, then it's better to integrate loadash or underscore in you application.
Add below code to your HTML before loading the controller file.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
After looking the response of http://tools.vcommission.com/api/coupons.php?apikey=e159f64e3dd49fddc3bb21dcda70f10c6670ea91aac30c7cb1d4ed37b20c45b8, below code will give you the array that matches the offer_name.
$http.get("http://tools.vcommission.com/api/coupons.php?apikey=e159f64e3dd49fddc3bb21dcda70f10c6670ea91aac30c7cb1d4ed37b20c45b8").then(function (response) {
$scope.filteredOffers = [];
var offerName = $stateParams.offer_name;
$scope.filteredOffers = _.filter(response.data, ["offer_name",offerName]);
})

Angular parse response from database

I have response from database:
{"status":"success","message":"Data selected from database","data":[{"id":1171,"sku":0,"word_one":"one word","description":"","word_two":"two word","mrp":0,"lang_one":"en","image":"","lang_two":"en","status":"Active","category":"[{\"text\":\"someone\"},{\"text\":\"sometwo\"}]","UserID":188},
...
{"id":1170,"sku":0,"word_one":"something","description":"","word_two":"some two","mrp":0,"lang_one":"en","image":"","lang_two":"en","status":"Active","category":"[{\"text\":\"ever\"},{\"text\":\"never\"}]","UserID":188}]}
Before I make post: angular.toJson($scope.category);
How I can show category something like this
{{category}} = someone, sometwo ?
Because actually I have string :
[{"text":"someone"},{"text":"sometwo"}]
[{"text":"ever"},{"text":"never"}]
...
You can use the below parsing to achieve what you want. Suppose json is the variable received from database.
var json = {"status":"success","message":"Data selected from database","data":[{"id":1171,"sku":0,"word_one":"one word","description":"","word_two":"two word","mrp":0,"lang_one":"en","image":"","lang_two":"en","status":"Active","category":"[{\"text\":\"someone\"},{\"text\":\"sometwo\"}]","UserID":188}]};
var data = json.data[0].category;
var jsonArray = JSON.parse(data);
var category = "";
jsonArray.map(function(obj, i ) {
if(i != 0) {
category += ",";
}
category += obj.text;
});
console.log(category)
At the end , You attach category to $scope.category.
This work:
var parsed = JSON.parse($scope.c.category);
var arr = [];
for(var x in parsed){
arr.push(parsed[x]);
}
$scope.c.category = arr;

Resources