I'm trying to access the elements of a list stored in ViewBag as follows:
function equipamentoTemControle() {
for(i = 0; i < #ViewBag.qtdEquipamentos; i++) {
var contratocod = #ViewBag.DadosEquipamentos[i].contratocod;
}
}
But when trying to access contratocod of attribute index i the Visual Studio says that the variable i does not exist. How do I access ?
Use
var jsonObj = #Html.Raw(Json.Encode(ViewBag.qtdEquipamentos));
and then
for (i = 0; i < jsonObj .length; i++) {
var contratocod = jsonObj[i].contratocod;
}
Hope this work first encode model in a JSON and then iterate.
Related
I used the Gson library to create a json from java and it returns me something like that:
[{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}]
How can I parse and access to the values in my js file?
i use a lot w3schools site here
var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>JSON Object Creation in JavaScript</h2>
<p id="demo"></p>
Getting these is actually pretty easy in JS because JSON Objects are just considered Objects by js.
You can do this like so:
for (let i = 0; i < myArray.length; i++) {
let currObj = myArray[i];
let keys = Object.keys(currObj);
for (let j = 0; j < keys.length; j++) {
let myValue = keys[j];
doSomethingWithMyValue(myValue);
}
}
That will get every value for every key in every object in your array. This should give you a pretty good baseline for how these objects work.
Edit: Worth noting, there is also a Object.values(obj), method, which will return a list of all the values in your object in order, but it currently has very poor browser support, so you are much safer using Object.keys and then iterating over the keys like I showed above.
It's hard to say what you want to do with the data, and whether or not there are duplicate titles, as in your example. However...
var a = [{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}];
a.forEach(function(v) {
doSomething(v.title, v.author);
});
should work
With a for loop
If you get the JSON as an array
var json = [{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}];
for (var i = 0; i < json.length; i++) {
console.log(json[i].title, json[i].author);
}
If you get the JSON as a string
var string = '[{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}]';
var json = JSON.parse(string);
for (var i = 0; i < json.length; i++) {
console.log(json[i].title, json[i].author);
}
//Here an example ---
var elements=[{id:123, name:'lorem'},{id:456, name:'ipsum'},{id:998, name:'verrugas'}];
for (item in elements){
console.log(elements[item].name);
}
Ok, that was a very noob question.
Firstly, to access to the values I have to do something like
data.title
In my case I had an array so I had to use something like
var j = JSON.parse(data);
for (var i = 0; i < j.length ; i++) {
console.log(j[i].title);
}
When I run for the first time this function it said "JSon unexpected identifier Object, that because Gson was returning already a json and javascript was trying to create a json of a json, so I removed the JSON.parse(data) and now it works!
Thanks u all
I wanted to make a code that will easily save all variables. Normally i would need for 60 variables about 120 lines. Not very efficient. I decided to try to make one function with array to try to save all variables. It doesnt seem to work.
My problem is that loaded variables are string, but i need them to be float.
var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;
function save(){
for (var i = 0; i < variablelength; i++){
localStorage[variablelist[i]] = window[variablelist[i]];
}
}
function load(){
for (var i = 0; i < variablelength; i++){
window[variablelist[i]] = localStorage[variablelist[i]];
}
}
I have tried
window[variablelist[i]] = localStorage[parseFloat(variablelist[i])];
Nothing has worked. It is still a string. Any ideas ?
First of all, it hurts me to see so much stuff stored on the window object like that. You should really give that a re-think!
LocalStorage is a way of storing a key-value pair to the browsers memory for access later. The only catch is that the value has to be a string.
You can get around this my using the JSON.stringify and JSON.parse function:
var objectToSave = {
key1: 'something',
key2: 'something else'
};
localStorage.setItem('myObject', JSON.stringify(objectToSave));
console.log(localStorage.getItem('myObject')); // What is stored
console.log(JSON.parse(localStorage.getItem('myObject'))); // The parsed object
Otherwise, if you are set on saving all of the individual variables, you are not far off, you just need to use the getItem and setItem:
var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;
function save(){
for (var i = 0; i < variablelength; i++){
localStorage.setItem(variablelist[i], window[variablelist[i]]);
}
}
function load(){
for (var i = 0; i < variablelength; i++){
window[variablelist[i]] = localStorage.getItem(variablelist[i]);
}
}
Use localStore.setItem() and localStore.getItem() to store and load items. Also use JSON.stringify() and JSON.parse() to convert objects to text, and then restore them back to objects.
var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;
function save(){
for (var i = 0; i < variablelength; i++){
localStorage.setItem(variablelist[i], JSON.stringify(window[variablelist[i]]));
}
}
function load(){
for (var i = 0; i < variablelength; i++){
window[variablelist[i]] = JSON.parse(localStorage.getItem(variablelist[i]));
}
}
I'm trying to write a function that accesses an object inside of an array inside of an object and then push that into an array.
This is the code I have right now:
Javascript
stuff: function (index1, index2) {
for (var i = 1; i < index1.length; i++) {
state[index2].push(foodData[index1][i].name);
}
}
When I run storage.stuff('ingredientsToInclude', 'desired') I get the following error:
Cannot read property 'name' of undefined
However, if I access foodData["ingredientsToInclude"][1].name in the console it returns the correct value.
Not sure the reason for the discrepancy.
you are looping over string 'ingredientsToInclude' instead of actual array foodData['ingredientsToInclude'].
So change for (var i = 1; i < index1.length; i++) { to for (var i = 1; i < foodData[index1].length; i++) {
I have a listview div on screen and I have added itemDataSource to it successfully
var lettersList = new WinJS.Binding.List(jsonArrayForClearance);
var list_ = document.getElementById("prodListView").winControl;
list_.itemDataSource = lettersList.dataSource;
list_.itemTemplate = document.getElementById("tileTemplate");
list_.forceLayout();
Now in each item I have added a custom input type for user to specify(using template). I want to iterate through all the items of list and obtain the value of that input type in an array.
how can I do it?
EDIT: My question is to access custom input type declared in list items. As such we use following code to access any input type named "inpT"
document.getElementById('inpT');
but how to access the same from list item? can I use Following code(as suggested by user2608614)
var listView = document.getElementById("prodListView").winControl;
var list = listView.itemDataSource.list;
for (var i = 0; i < list.length; i++) {
var item = list.getAt(i);
item.getElementById('inpT');
}
You can iterate through the list elements like this:
var listView = document.getElementById("prodListView").winControl;
listView.itemDataSource.getCount()
.done(function(count) {
for (var i = 0; i < count ; i++) {
listView.itemDataSource.itemFromIndex(i)
.done(function (item) {
//***item will contain your property
});
}
});
Is not the best solution as it make it difficult to chain the promises, I'm also looking for a better one. But it works.
Since you're using a Binding.List you can just iterate through that much like an array.
var listView = document.getElementById("prodListView").winControl;
var list = listView.itemDataSource.list;
for (var i = 0; i < list.length; i++) {
var item = list.getAt(i);
// do something with this item
}
The only thing to remember is that it doesn't support [] and instead you have to use .getAt() and .setAt().
I using JavaScript JSON library to parse JSON encoded array, received via POST.
Here is my code:
var itemsRequest = '[{"id":"142"},{"id":"152"}]';
var items = JSON.parse(itemsRequest);
for(var i = 0; i<items.count(); i++)
{
var item = items[i];
alert(item.id);
}
I am not sure why, but the parser is just not liking that. How can I get it to parse?
Try items.length instead of items.count().
An array doesn't have a count method. Use the length property:
for (var i = 0; i < items.length; i++) {
Demo: http://jsfiddle.net/Guffa/Rt4db/
Below is the very good way to do:
var itemsRequest = '[{"id":"142"},{"id":"152"}]';
var items = eval(itemsRequest); //Converted to actual JSON data
for (var item in items) {
alert(items[item]['id']);
}
Hope this is very helpful, thanks