How to convert dictionary to a string angularjs - angularjs

I am currently working on my project using angularjs. I got everything already it is just that, i need to convert the dictionary list to a string separated by comma. I can only do this using python.
[{"name":"john"},{"name":"mark"},{"name":"peter"}]
I want to convert them to string
"john,mark,peter"
I would really appreciate your help. :)

.map and then .join will do
var array = [{"name":"john"},{"name":"mark"},{"name":"peter"}];
var names = array.map(function(item) {
return item.name;
}).join(',');

The map() method creates a new array with the results of calling a function for every array element. Use this to loop and then add that value to a variable.
var dict=[{"name":"john"},{"name":"mark"},{"name":"peter"}];
var string;
dict.map(function(value){
//do any stuff here
string+=value["name"]+",";
});
console.log(string);

Try map function to concatenate the values:
var dict=[{"name":"john"},{"name":"mark"},{"name":"peter"}];
var str="";
dict.map(function(a){
str+=a["name"]+",";
});
//feels ironical as question has AngularJS tag
document.getElementById("log").innerText=str;
<div id="log"></div>

You can simply iterate over each key-value pair and concat the extracted value with comma.
var obj = [{"name":"john"},{"name":"mark"},{"name":"peter"}]
var result = '';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
result += obj[p].name + ",";
}
}
result = result.replace(/,$/g,''); // to trim trailing comma

Related

How can I access an element from an array?

var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1Ow_rhF3sibKL3OAQRXpK6LLZDjMOhW-5DKyWWiN5iZg/edit#gid=638513192');
var data = SpreadsheetApp.setActiveSheet(ss.getSheetByName('Graficos'));
Logger.log(SpreadsheetApp.getActiveSpreadsheet());
var ergo = data.getRange(3,2,4,1);//B3:B6 '
My guess to access the elements was to call var i = ergo[0]; but it didn't work. Do I have to declare ergo using a different syntax?
You need to use getValues() on the range, which will return a 2-dimensional array.
var ergo = data.getRange(3,2,4,1).getValues();
Also, you're not coding efficiently as you're essentially duplicating actions in your first two lines. Take a look at this refactoring:
function test() {
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1Ow_rhF3sibKL3OAQRXpK6LLZDjMOhW-5DKyWWiN5iZg/edit#gid=638513192');
var data = ss.getSheetByName('Graficos');
ss.setActiveSheet(data); // There doesn't seem to be a need to do this, so maybe delete this line
var ergo = data.getRange(3,2,4,1).getValues(); //B3:B6
}

AngularJS Filter expression replacing with variable instead

I have a table object and I want to filter out a particular "index" row using filter function as shown below.
However, $controller.expression is not working out.
IF `$controller.expression = "3";
It would work. But not
$controller.expression = "3,4";
$controller.expression = [3,4];
$scope.dataToBeTransfer = $scope.myDataTable.filter(function (el)
{
return el.index== $controller.expression;
});
So how do I solve this issue?
If you're going to use an array you need to loop through to see if el.index is included in the array. This is probably the easiest way to do it from the given code:
$scope.dataToBeTransfer = $scope.myDataTable.filter(function (el) {
return $controller.expression.includes(el.index);
});

swift - using .map on struct array

i have a struct array that i want "break up" into smaller arrays that can be called as needed or at least figure out how i can map the items needed off one text value.
the struct:
struct CollectionStruct {
var name : String
var description : String
var title : String
var image : PFFile
var id: String
}
and the array made from the struct
var collectionArray = [CollectionStruct]()
var i = 0
for item in collectionArray {
print(collectionArray[i].name)
i += 1
}
printing partArray[i].name gives the following result:
pk00_pt01
pk00_pt02
pk00_pt03
pk01_pt01
pk01_pt02
pk01_pt03
pk01_pt04
pk01_pt05
pk01_pt06
pk01_pt07
pk01_pt08
this is just some test values but there could be thousands of entries here so i wanted to filter the entire array just by the first 4 characters of [i].name i can achieve this by looping through as above but is this achievable using something like .map?
I wanted to filter the entire array just by the first 4 characters of
[i].name
You can achieve this by filtering the array based on the substring value of the name, as follows:
let filteredArray = collectionArray.filter {
$0.name.substring(to: $0.name.index($0.name.startIndex, offsetBy: 4)).lowercased() == "pk00"
// or instead of "pk00", add the first 4 characters you want to compare
}
filteredArray will be filled based on what is the compared string.
Hope this helped.
If you want to group all data automatically by their name prefix. You could use a reducer to generate a dictionary of grouped items. Something like this:
let groupedData = array.reduce([String: [String]]()) { (dictionary, myStruct) in
let grouper = myStruct.name.substring(to: myStruct.name.index(myStruct.name.startIndex, offsetBy: 4))
var newDictionart = dictionary
if let collectionStructs = newDictionart[grouper] {
newDictionart[grouper] = collectionStructs + [myStruct.name]
} else {
newDictionart[grouper] = [myStruct.name]
}
return newDictionart
}
This will produce a dictionary like this:
[
"pk00": ["pk00_pt01", "pk00_pt02", "pk00_pt03"],
"pk01": ["pk01_pt01", "pk01_pt02", "pk01_pt03", "pk01_pt04", "pk01_pt05", "pk01_pt06", "pk01_pt07"],
"pk02": ["pk02_pt08"]
]
Not sure if i am understanding you correctly but it sounds like you are looking for this...
To create a new array named partArray from an already existing array named collectionArray (that is of type CollectionStruct) you would do...
var partArray = collectionArray.map{$0.name}

Parse this string to an array of Guids or strings

I'm working with Sitefinity and when you add a custom Tags attribute to a Page it results in the following string value:
"[\"1f3560ca-84b9-6a87-9ce5-ff00009465c7\",\"893460ca-84b9-6a87-9ce5-ff00009465c7\"]"
Does anyone have a clever conversion method that can convert this string into an array of guids or strings?
I would write something that splits by , and removes the brackets... I just feel there must be a better way though but it doesn't come to mind.
You can use Microsoft JavaScriptSerializer class, which can help you turn a JSON string into objects.
var serializer = new JavaScriptSerializer();
var deserializedResult = serializer.Deserialize<List<string>>(tags);
This is my current solution...
string tags = "[\"1f3560ca-84b9-6a87-9ce5-ff00009465c7\",\"893460ca-84b9-6a87-9ce5-ff00009465c7\"]";
return tags
.Replace("[", "")
.Replace("]", "")
.Replace(" ", "")
.Replace("\"", "")
.Split(',')
.Where(t =>
{
Guid g;
return Guid.TryParse(t, out g);
}).Select(t => new Guid(t)))
Have you tried casting it to TrackedList?

Loop through nested array wordpress json api

Hi i want to loop through comments in a json file (wordpress json api) the problem is i want to use the each function to display all the comments. How i loop with the each function true a nested array i can't find the solution. now i use the following code, but thats only showing the first item
var html2 ='<p>'+ data.post.comments[0]["name"] +'<br><p>'+ data.post.comments[0]["content"] +'</p>';
$( ".content>.comments" ).append(html2);
the json file:
http://indinxperlo.nl/api/get_post/?post_id=399
Use jquery each:
var html = [];
$.each(data.post.comments, function(key,val){
html.push('<p>'+val["name"]+'</p>');
});
$(".content>.comments").append(html.join(''));
If you want to control number of max comments shown do this:
var html = [];
var count = 0;
$.each(data.post.comments, function(key,val){
html.push('<p>'+val["name"]+'</p>');
if (count == 5) {return false;}
count++;
});
$(".content>.comments").append(html.join(''));

Resources