how to make index dynamic for json objects - javascript

i'm tring to dynamically display eveyrthing that comes back from the server, however to get it displaying i have to explicitly write in the index of the object i'm trying to access, how can i make this dynamic so it goes through them all?
i am Using AngularJS, Express, and Mongoose.
here is the code snippet where the index i want to change on its own located.
app.controller('MainController', ['$scope', 'whipmeet', function($scope, whipmeet) {
whipmeet.getWhipmeets(function(JSON){
$scope.meetinfo = JSON;
$scope.meetparts {
name = JSON.data["0"].name,
location = JSON.data["0"].location,
car = JSON.data["0"].car,
date = JSON.data["0"].date,
time = JSON.data["0"].time,
type = JSON.data["0"].type,
stock = JSON.data["0"].stock
};
what i'm trying to achieve is that the ["0"] index change dynamically to get all the indexes of the objects so i can get those zeroes to go 1 to 2 to 3 and so on untill there are no more

There are few options.
From my understanding, you are trying to iterate through the JSON object that is returned to you.
You can either use:
var meetpartList = [];
JSON.foreach(function(d) {
// do your parsing here
newObject = {};
newObject.name = d.name;
// etc..
meetpartList.append(newObject);
});
or you can use:
for (int i = 0; i < numberOfIndicesInJson; i++) {
// get values using JSON[i + ""].key;
}
to do something similar as above to create a list of meets.
Then you can use that list of meets to render into your view using ng-repeat, which I hope is the solution you're looking for?

Related

jQuery and XML, find object that contains children with multiple specific values

For a project I have data stored in XML like this:
<xml>
<sprites>
<sprite>
<name>Tile1</name>
<lat>1</lat>
<lng>2</lng>
</sprite>
<sprite>
<name>Tile2</name>
<lat>3</lat>
<lng>4</lng>
</sprite>
</sprites>
<xml>
Through jQuery I want to get a tile object that matches two child values, the lat and lng values.
I found this post which was of great help, but sadly it only has an example of how to search for one matching value. Here's the code I have up to now:
// xml stored in 'xml' var
var findLat = 3;
var findLng = 4;
var mapSprites = $(xml).find("sprites");
var getSprite = $(mapSprites).find("sprite").filter(
function() {
return $(this).find('lat').text() == findLat;
},
function() {
return $(this).find('lng').text() == findLng;
}
);
Sadly getSprite is undefined, as I'm guessing you can't use the filter function as I've tried to use it? The example I linked to has one function as filter and seems to work, but comma separating doesn't seem to work as an AND, which is what I need.
The goal is to be able to give the function a lat and lng value and me being able to extract the <name> value.
Would be thankful for a push in the right direction, I'm pretty new to XML and parsing it through jQuery.
filter does not take multiple arguments. So combine it into one using "and".
var findLat = 3;
var findLng = 4;
var mapSprites = $(xml).find("sprites");
var getSprite = mapSprites.find("sprite").filter(
function() {
const node = $(this);
return Number(node.find('lat').text()) === findLat &&
Number(node.find('lng').text()) === findLng;
}
);

How to get selected values of Kendo Multi Select?

I'm using Kendo multi select as follow but i can't get selected values
var multiselect = $("#SelectRoles").data("kendoMultiSelect");
var selectedData= [];
var items = multiselect.value();
for (var itm in items)
{
selectedData.push(itm);
}
but array selectedData return indices of items in multiselect not values .
You can also assign the array, returned from the value() method, directly to the variable, e.g.:
var ms = $("#multiselect").kendoMultiSelect({
value: ["1", "2"]
}).data('kendoMultiSelect');
var selectedItems = ms.value();
console.log(selectedItems); // ["1", "2"]
Use this other one returns indices.
var multiselect = $("#SelectRoles").data("kendoMultiSelect");
var selectedData= [];
var items = multiselect.value();
for (var i=0;i<items.length;i++)
{
selectedData.push(items[i]);
}
Your original code doesn't look wrong. Are you sure you are getting only indices? Perhaps you should post your MultiSelect code as well. I found this question because I had the same problem and used the other answers for reference, but I found them overcomplicated. So let me answer in another complicated way :)
Here's what I've got. I know it's more code than you need, but I think it's important to see the full picture here. First let me set this up. There's a problem with the Kendo().MultiSelect.Name("SomeName") property if you are using it more than once. "Name" sets not only the html name, but the id as well, and you never want two ids with the same identifier. So in my code, I am appending a unique Id to my MultiSelect.Name property to ensure a unique id. I am putting the MultiSelect in each row of a table of people. I am showing this to make sure you are using the DataValueField property so you are able to get the selected values (not the text you see in the ui). If you are just showing a list of text values with no id behind them, perhaps that is why you are getting the wrong data?
#foreach (var cm in Model.CaseMembers)
{
<tr>
<td>
#(Html.Kendo().MultiSelect()
.Name("IsDelegateFor" + cm.CaseMemberId)
.Placeholder("is a delegate for..")
.DataTextField("FullName")
.DataValueField("CaseMemberId")
.BindTo(Model.Attorneys)
)
</td>
</tr>
}
then, later on, in my jQuery where I attempt to extract out the DataValueField (CaseMemberId), which is the array of selected values of the MultiSelect...
var sRows = [];
$('#cmGrid tr').each(function () {
// 'this' is a tr
$tr = $(this);
// create an object that will hold my array of selected values (and other stuff)
var rec = {};
rec.IsADelegateFor = [];
// loop over all tds in current row
$('td', $tr).each(function (colIndex, col) {
if (colIndex === 3) {
// make sure our MultiSelect exists in this td
if ($(this).find("#IsDelegateFor" + rec.CaseMemberId).length) {
// it exists, so grab the array of selected ids and assign to our record array
rec.IsADelegateFor = $(this).find("#IsDelegateFor" + rec.CaseMemberId).data("kendoMultiSelect").value();
}
}
}
// add this tr to the collection
sRows.push(rec);
}
so this is all a super verbose way of saying that this single line, as the other people mentioned works perfectly to grab the ids. There is no need to iterate over the .value() array and push the contents to another array!
rec.IsADelegateFor = $(this).find("#IsDelegateFor" + rec.CaseMemberId).data("kendoMultiSelect").value();
So in your original code, there is no reason the following should not work,
var multiselect = $("#SelectRoles").data("kendoMultiSelect");
var selectedData = [];
selectedData = multiselect.value();
console.log(selectedData);
unless
you don't have your MultiSelect set up properly in C# with DataValueField
you have multiple MultiSelects on the page with the exact same id and it's reading from a different one than you think.
You don't even have value fields, just a list of text.
var selected = $("#multi").data("kendoMultiSelect").value();
The solution given by volvox works.
Below is jquery version,
var multiselect = $("#SelectRoles").data("kendoMultiSelect");
var selectedData= [];
var items = multiselect.value();
$.each(items ,function(i,v){
selectedData.push(v);
});

Javascript storing multiple fields in an array

I was wondering if it's possible to store multiple different fields in a dynamic array using Javascript.
In Informix it is called a dynamic array of records and it is accomplished like this
# define array of record
la_data dynamic array of record
var_idno integer,
var_desc char(30)
end record
# populate array of record
for lv_cnt = 1 to 10
let la_data[lv_cnt].var_idno = lv_cnt
let la_data[lv_cnt].var_desc = "dummy data"
end for
# use stored data
display la_data[5].var_idno # will output 5
display la_data[5].var_desc # will output dummy data
How would I do something similar (or completely different) using Javascript
// define array of record
var la_data = [];
// populate array of record
for (var lv_cnt = 1; lv_cnt <= 10; lv_cnt++) {
// This initializes an object we can put your properties on
la_data[lv_cnt] = {};
la_data[lv_cnt]['var_idno'] = lv_cnt;
la_data[lv_cnt]['var_desc'] = "dummy data";
}
// use stored data
console.log(la_data[5].var_idno) // will output 5
console.log(la_data[5].var_desc) // will output dummy data
Fiddle: http://jsfiddle.net/xxqkfuot/
As you can see in other answers there are simpler ways to do this but I was attempting to keep the code as similar as possible so you could see the connection between the lines.
I suppose you could create sometihng like a dynamic array in javascript, but the simplest and most idiomatic thing to do with pure javascript would be to use a list:
var list = [];
for (i = 0; i < 10; i++)
list.push({var_idno: i, var_desc: 'Dummy data'});
JavaScript is loosely typed so this is actually too easy to do.
var one = 1;//int
var two = "String";//String
var three = {
"name": "Foo",
"address": "bar"
};//Object
var array = [one, two, three];
console.log(array[0]);//1
console.log(array[1]);//String
console.log(array[1]);//[Object]

How to get the value from JSON in JS

I'm trying to get the "formatted_address" value from this
JSON file. I'm new to this and found the documentation quite confusing. The code I have now is the following where the variable "location" is the url generated like the one above.
$.getJSON(location, function( data ){
stad = data.results.formatted_address;
console.log(stad);
});
How would I achieve this?
results is an array, so you need to access it as one. Given your example with only one item, you can access it directly by index:
var stad = data.results[0].formatted_address; // = "'s-Hertogenbosch, Netherlands"
If there were multiple items in the array you would need to loop through them:
for (var i = 0; i < data.results.length; i++) {
var stad = data.results[i].formatted_address;
// do something with the value for each iteration here...
}
$.each(data.results,function(key,value){
console.log(value.formatted_address); //'s-Hertogenbosch, Netherlands
});

Dynamically construct array based on user input - Javascript/jQuery

I have a list of US regions set up as checkboxes. When a user submits the form, I need an array of associated states. This array is used for comparing to another array in my SQL tables.
Using jQuery or javascript, what's the best way to go about this?
I've got the general idea I believe:
//populate region to state arrays here
$("input[name='region']").each(function () {
if ($(this).is(':checked')) {
// ADD TO SUPER ARRAY OF ALL REGIONS
// (this is where I need help)
}
});
Thanks in advance!!
PS. I tried using the input values var regionValue = $(this).attr('value') to identify each array, but I'm having issues with dynamically named arrays since all my functions are in static classes.
Edited to reflect the new information and incorporating GenericTypeTea's comment:
Assuming the ID of each checkbox is set to the region name, how about:
var regionStates = {};
regionStates['northeast'] = ['AB', 'CD', 'EF'];
regionStates['mountains'] = ['GH', 'IJ', 'KL'];
// etc...
var selectedStates = [];
$("input[name='region']:checked").each(function () {
var region = regionStates[this.id];
for (var i = 0; i < region.length; ++i) {
selectedStates[selectedStates.length] = region[i];
}
});
Using this, selectedStates will contain all the states of all regions that are selected.
Apologies for not knowing any real US state abbreviations.

Categories