I have an object which looks like this.
{
"class_details":{
"class_1":{student_4":"<name>","student_3":"<name>,student_2":"<name>","student_1":"<name>},
"class_2":{"student_1":"<name>},
"class_0":{student_2":"<name>","student_1":"<name>
}
}
I am trying to use a loop to iterate over the classes but I am not able find a perfect way to do it.
I cant do something like this,
for(int i=0; i < $scope.rounds.class_details.length;i++)
console.log($scope.rounds.class_details.round_[i])
So i am doing this
for(int i=0; i < $scope.rounds.class_details.length;i++)
console.log(Object.keys($scope.rounds.class_details)[i])
But here the class details do not come in an order and this matters in my case.
It would be great if there is an alternative similar to
for(int i=0; i < $scope.rounds.class_details.length;i++)
console.log($scope.rounds.class_details.round_[i])
or if there is a simple way to sort the JSON class details.
To get the keys in ascending order do:
var class_details_keys = Object.keys($scope.rounds.class_details);
class_details_keys = class_details_keys.sort(function(a,b) {return (+a.substring(6)) - (+b.substring(6));});
for(int i=0, length = class_details_keys ; i < length;i++)
console.log($scope.rounds.class_details[class_details_keys[i]]);
This will return your classes in ascending order by taking the substring after 'class_' and ordering them. You can't do a simple string comparison since "4" > "10" will return incorrect result.
The simplest way to read data like you're hoping is the following:-
for(int i=0; i < $scope.rounds.class_details.length;i++)
console.log($scope.rounds.class_details["round_" + i]);
This is because you can access an objects property in two ways: -
Allows you to pass a dynamic value in (i.e. the i value)
object["property" + withVariable + "Name"]
Simple, readable way where you know the property.
object.propertyName
First, fix json. NOTE: there are some quotes missing in the original code.
"class_details":{
"class_1":{
"student_4":"<name>",
"student_3":"<name>",
"student_2":"<name>",
"student_1":"<name>"
},
"class_2":{
"student_1":"<name>"
},
"class_0":{
"student_2":"<name>",
"student_1":"<name>"
}
}
Followed to this:
//parse to json. Assume the
//'body' is the json data received
//if there is data in body
if(body){
//parse body
var parsed_body= JSON.parse(body);
//your data
var class_details = parsed_body.class_details;
var class_2_student_1 = parsed_body.class_details.class_2.student_1;
//if you want to print json directly to the front-end,
//then Object Object may be printed out. to prevent this,
//one could use .toString() to convert Object to String.
}
else{}//do something if no data in the body
Related
I have an Array of Arrays populated from C# Model:
var AllObjectsArray = [];
#foreach(var Cobject in Model.ObjectList)
{
#:AllObjectsArray.push(new Array("#Cobject.Name", "#Cobject.Value", "#Cobject.Keyword"));
}
var SelectedObjects = [];
uniqueobj.forEach(function (element) {
SelectedObjects.push(new Array(AllObjectsArray.filter(elem => elem[0] === element))); //makes array of selected objects with their values(name,value,keyword)
});
I am trying to get second parameter of each and every inner Array and add it to new array containing those elements like this:
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][0]) //problem here i think
};
Unfortunately, on:
alert(ValuesArray + " : " + SelectedObjects);
I get nothing for ValuesArray. The other data for SelectedObjects loads properly with all three parameters correctly returned for each and every inner Array,so it is not empty. I must be iterating wrongly.
EDIT:
SOme more info as I am not getting understood what I need.
Lets say SelectedObjects[] contains two records like this:
{ name1, number1, keyword1}
{ name2, number2, keyword2}
Now, what I need is to populate ValuesArray with nane1 and name2.
That is why I was guessing I should iterate over SelectedObjects and get SelectedObject[i][0] where in my guessing i stands for inner array index and 1 stands for number part of that inner array. Please correct me and put me in the right direction as I am guesing from C# way of coding how to wrap my head around js.
However SelectedObject[i][0] gives me all SelectedObject with all three properties(name, value and keyword) and I should get only name's part of the inner Array.
What is happening here?
Hope I explained myself better this time.
EDIT:
I think I know why it happens, since SelectedObjects[i][0] returns whole inner Array and SelectedObjects[i][1] gives null, it must mean that SelectedObjects is not Array of Arrays but Array of strings concatenated with commas.
Is there a way to workaround this? SHould I create array of arrays ddifferently or maybe split inner object on commas and iteratee through returned strings?
First things first, SelectedObjects[i][1] should rather be SelectedObjects[i][0].
But as far as I understand you want something like
var ValuesArray = [];
for (let i = 0; i < SelectedObjects.length; i++) {
for(let j = 0; j <SelectedObjects[i].length; j++) {
ValuesArray.push(SelectedObjects[i][j]);
}
};
In this snippet
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][1]) //problem here i think
};
You're pointing directly at the second item in SelectedObjects[i]
Maybe you want the first index, 0
I need to pass a string array content through URL. The String array can contain 100 - 10000 values. I got the similar question link but problem in my case it contains large amount of data.
Using comma (,) is the best way to pass the values or is there any other way to solve this problem.
I am using this in javascript function where String array contains all the selected checkbox list values.
<script type="text/javascript">
function doResend(){
var checkboxes = document.getElementsByName('selectedId');
var vals = "";
for (var i=0, n=checkboxes.length;i<n;i++) {
if (checkboxes[i].checked){
vals += ","+checkboxes[i].value;
}
}
if (vals){
vals = vals.substring(1);
window.open('resendSelectedSMS.do?smsId='+vals,"mywindow","status=1, height=335, width=400',resizable=0");
}else{
alert("Select atleast one id");
}
}
</script>
Best method is using get - post :
http://www.w3schools.com/tags/ref_httpmethods.asp
something that looks like that :
/test/demo_form.asp?name1=value1&name2=value2
I am using JSON stringify, here is my code:
var lista={};
for(var i=0; i < arr.length; i++){
lista[i]=[];
//lista[i].push('imagen:'+arr[i].id);
lista[i].push('nick:'+arr[i].nick);
lista[i].push('tlfno:'+arr[i].tlfno);
lista[i].push('nombre:'+arr[i].nombre);
lista[i].push('descripcion:'+arr[i].descripcion);
lista[i].push('direccion:'+arr[i].direccion);
lista[i].push('fecha:'+arr[i].fecha);
lista[i].push('estado:'+arr[i].estado);
lista[i].push('tipoimagen:'+arr[i].tipoimagen);
//lista[i].push('imagen:'+arr[i].imagen);
}
var json = JSON.stringify(lista);
console.log(json);
I am getting this output:
{"0":["nick:pepe","tlfno:678909897","nombre:dsfdfsf","descripcion:dsdsdsd","direccion:fdfdf","fecha:fdfdf","estado:1","tipoimagen:image/jpeg"]
but is wrong because it would be like this:
{"0":["nick":"pepe" with double quotes, somebody knows how to show this double quote? Thanks
I'm guessing you're trying to push objects into that array, not strings
lista[i].push( {nick: arr[i].nick} );
That would give you something like
{"0":[{"nick":"pepe"}]}
note that {"0":["nick":"pepe"... is not valid, so you won't be getting that
FIDDLE
I've been searching for an answer but couldn't find it.
I have a json like this:
followersperdate{
'date2012-08-29': 16823,
'date2012-07-09': 15571,
'date2012-07-07': 15528,
'date2012-06-25': 15237,
'date2012-04-19': 13283,
'date2012-03-16': 12999,
etc.
}
and I want to get the values; but everytime I make the request, I recieve other dates. I don't know how to get the values.
I've tried with jsonpath but didn't work.
This is pretty trivial using DefiantJS (http://defiantjs.com). This lib extends the global object JSON with the method "search". Using this method, you can search a JSON structure, regardless of depth for values. It returns an array with the matches (empty array if no matches were found).
To get acquainted with XPath, check out this valuable resource;
http://www.defiantjs.com/#xpath_evaluator
Check out this fiddle;
http://jsfiddle.net/hbi99/DKuAQ/
var data = {
"date2012-08-29": 16823,
"date2012-07-09": 15571,
"date2012-07-07": 15528,
"date2012-06-25": 15237,
"date2012-04-19": 13283,
"date2012-03-16": 12999
},
res = JSON.search( data, '//*' ),
str = '';
for (var i=0; i<res.length; i++) {
str += res[i] +'<br/>';
}
document.getElementById('output').innerHTML = str;
I have a variable that is created by Flowplayer and available via javascript. If I write the variable to the page directly it just returns 'object Object' so I am assuming this is an array. If I don't know the names of any of the objects inside the array, how can I parse out the data inside?
I know I am missing something really fundamental here, but I don't think I have ever had to get data from an array not knowing what it contains.
Notes:
What I am trying to do is get the onCuePoint caption data embedded
into an RTMP video stream
.valueOf() returns the same thing
Here is the code I am using that returns 'object Object':
streamCallbacks: ['onFI'],
clip:
{
live:true,
provider: 'rtmp',
autoPlay: true,
url:'test1',
onFI:function(clip, info)
{
document.getElementById("onFI").innerHTML += "Data: " + info;
}
}
Thank you
If what you are asking is how you iterate over the contents of an array, you can do so in plain javascript like this:
var arr = [1,2,3];
for (var i = 0; i < arr.length; i++) {
// arr[i] is each item of the array
console.log(arr[i]);
}
Just because something is of type Object does not necessarily mean that it's an array. It could also just be a plain object with various properties on it. If you look at the info argument in either the debugger or with console.log(info), you should be able to see what it is.
You need to iterate through your array and get the results one by one, replace your onFI function with this :
onFI:function(clip, info)
{
var data = "";
// For each value in the array
for (var i = 0; i < info.length; i++)
{
// Add it to the data string (each record will be separated by a space)
data += info[i] + ' ';
}
document.getElementById("onFI").innerHTML += "Data: " + data;
}