I'm trying to parse something like this
{
"popular result":[
{"term":"Summer","url":"http://summer.com"},
{"term":"Autumn","url":"http://autumn.com"},
{"term":"spring","url":"http://spring.com/"},
{"term":"winter","url":"http://winter.com/"}]
}
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/Controls/GetPopularSearches', function (json) {
for (var i = 0; i < json.length; i++) {
$.each(myJson.i, function (key, value) {
alert(value.term);
});
}
});
});
</script>
but nothing happened! Because is array in array! Please let me know how to do this
Arrays and objects are different things. You will want to investigate them tons more before things get really challenging.
Assuming json really does equal the object you provide (in JSON those show up as {}), then json['popular result'] (you could use a . if there wasn't a space) is the array (in JSON those show up at []) you want to traverse.
For some reason, this confusion got you looping over an object (not going to get you anywhere as length is rarely defined for it) and then (ignoring the typo on myJson), you started looping over something that didn't exist (which didn't crash b/c it never got there).
Cleaning it up...
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/Controls/GetPopularSearches', function (json) {
for (var i=0;i<json['popular result'].length;i++) {
alert(json['popular result'][i].term + ' points to the URL ' + json['popular result'][i].url);
}
});
});
</script>
Notice how the alert references the json object (that's your variable name), the popular result array, then [i] is the "row" in that array, and the term/url element of the object on that row.
NOTE: Running something with a ton of alerts as you're debugging is annoying. Check out console.log.
You don't need $.each and you need to loop over the array set as the value of popular result which is inside a containing object.
$.getJSON('/Controls/GetPopularSearches', function (json) {
var arr = json['popular result'];
for (var i = 0, l = arr.length; i < l; i++) {
console.log(arr[i].term);
}
});
Demo.
Check this fiddle
var jsontext =
'{"popularresult":[{"term":"Summer","url":"http://summer.com"},{"term":"Summer","url":"http://summer.com"}]}';
var getContact = JSON.parse(jsontext);
for (i = 0; i < getContact.popularresult.length; i++) {
alert(getContact.popularresult[i].term);
}
http://jsfiddle.net/ae8gd/
If you get the jsonObject as shown then
var JsonArray=json.popular; //get jsonArry
$.each(JsonArray,function(i,val){
// do logic
});
To parse json use JSON.parse();
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'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
});
I want to use the values that I get from a request, but the response object is a local variable (an array). Therefore I create this global array:
<script type="text/javascript">
var response = [];
as you see, right under the script opening tag, so it is global. Then in the function where I have the response I added this:
jsonResponse.forEach(function(element){
response[element.size] = element.id;
});
And then added this, with the purpose to make use of the values that I've got in my global var from the response object:
getIdOfProductBySize: function() {
var selectedIndex = document.getElementById('dropdown_options').value;
for (var key in response) {
if (key != selectedIndex) {
continue;
} else {
return response[key];
}
}
}
Doesn't work, so I started going step by step (of the order I add the new things) and I noticed that the script breaks after the 2nd thing that I add (where the forEach is).
Maybe I am not declaring the global variable correctly, or maybe I cannot access it this way, or maybe I don't assign the values to it in the correct way, I don't know, so I am asking if someone can give me a hint how to make use of all this working together?
Try this:
var response = {key1: value1};
var i = 2;
jsonResponse.forEach(function(entry) {
console.log(entry);
response["key"+i] = entry.id;
i++;
});
var index;
for (index = 0; index < response.length; ++index)
{
console.log(response[index]);
if(response["key"+index] !== selectedIndex)
continue;
else
return response["key"+index];
}
Looks like you're going to need a two dimensional array.
Looks to me like your "key" value is undefined.
before:
for (var key in response) {
try:
var k=response.whatever;
If that makes sense?
response[element.id] = element.size;
Try this one, i believe element.size returns the actual size of an element and is not what you want to use as index in an array.
var members = [
['Fred G. Aandahl', '1951-1953', 'North Dakota'],
['Watkins Moorman Abbitt', '1948-1973', 'Virginia'],
];
I need to create like this dynamically, I am using the following code to do that:
var data = new array();
var members = [];
$.each(data, function (i, elem) {
data.push(elem["p_age"], elem["p_name"], elem["p_date"]);
members.push(data);
});
console.log(members);
}
I need to print this values, for that.
for(var x = 0; x < members.length; x++) {
console.log(members[i][0]);
console.log(members[i][1]);
console.log(members[i][2]);
}
so when i try this i get following.
[object][object][object][object][object][object]
I am not sure how is your code working! It has some error's if your already aware of.
Your code should work fine after you change to:-
var data = new Array();//Was an Error in your code
var members = [];
$.each(temp, function (i, elem) {
data.push(elem["p_age"], elem["p_name"], elem["p_date"]);
members.push(data);
});
console.log(members);
for (var x = 0; x < members.length; x++) {
console.log(members[x][0]);//Was an Error in your code
console.log(members[x][1]);
console.log(members[x][2]);
}
Secondly, how does data.push(elem["p_age"], elem["p_name"], elem["p_date"]); works for you? It should give you undefined.
Just to get myself clear I wrote down your code to a fiddle. Have a look.
Try
var members=[];
$.each(data, function(i, elem) {
members.push([elem["p_date"],elem["p_name"],elem["p_date"]]);
});
console.log(JSON.stringify(members))
This looks suspect:
$.each(data, function(i, elem) {
data.push(elem["p_date"],elem["p_name"],elem["p_date"]);
It looks like you're trying to iterate over data, pushing the elements back on to data. I imagine that the $.each() needs to iterate over something else.
I also question why you're pushing elem['p_date'] onto an array twice.
Because it is treating them as objects. Try using toString() method.
Hi use x instead of i for loop.
for(var x=0;x<members.length;x++){
console.log(members[x][0]);
console.log(members[x][1]);
console.log(members[x][2]);
}
It will work.
Not
var data=new array();
but
var data=new Array();
Array's class name is Array, but not 'array'.
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;
}