Javascript for loop alert value one by one - javascript

I have a trouble with looping the json array in JavaScript. How do I get only SG_J1001 and SG_LS01? Actually, I didn't get what I want. Result is come out like that [{"regis .......
var item = JSON.stringify(data['code']); //[{"registerCode":"SG_J1001"},{"registerCode":"SG_LS01"}]
for(var i=0;i < item.length; i++){
alert(item[i]);
}

Dont stringify, and use dot notation to access the property of each index:
for(var i=0;i < item.length; i++){
alert(item[i].registerCode);
}

Using jQuery you can do it like:
$.each(item, function(index,obj){
alert(obj.registerCode);
});
See EXAMPLE

Several correct posts here.
One more rendition:
for (var key in data.code)
alert(key.registerCode)

Related

Append param on loop javascript

I have a function that has a menu param
removeChildCheck:function(menu){
let removeArrayValues = [];
for(var i=0; i < this.checkbox.menu.length; i++){
removeArrayValues.push(this.checkbox.menu[i].value);
}
this.user.permissions = this.user.permissions.filter((i) => !removeArrayValues.includes(i));
},
when I used it like this removeChildCheck('dashboard') im getting length of undefined.
How can I append the param and loop on it? TIA
Do you mean to do:
this.checkbox[menu]
That is, access the property of checkbox that has the name stored in the variable menu? Keep in mind that:
this.checkbox.dashboard
is equivalent to
this.checkbox['dashboard']
and
menu = 'dashboard'
this.checkbox[menu]
As audiodude says, use array syntax: this.checkbox[menu].length
removeChildCheck:function(menu){
let removeArrayValues = [];
for(var i=0; i < this.checkbox[menu].length; i++){
removeArrayValues.push(this.checkbox[menu][i].value);
}
this.user.permissions = this.user.permissions.filter((i) => !removeArrayValues.includes(i));
},

How to iterate over a json array

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

How to iterate over JSON data

The following is my JSON data in a div:
[{"Identifier":"1","Label":"10 Day","Categories":"Standard","UpdatedBy":"Lno","UpdatedAt":"01-02-2013","RefId":"0","ComType":"1","Cs":["944"],"AM":"Error Message","Message":"asdfasdf","Combiner":[{"uniqueID":"1","type":"7","rule":""}]}]
I am accessing it through a JS object:
var myArrayVar=JSON.parse(document.getElementById("populateDT").innerHTML);
I want to iterate over this JS object. The following is my code, but it doesn't access my key/value fields:
for(var i=0; i<=myArrayVar.length;i++){
for(var j=0; j<=myArrayVar.Combiner.length; j++){
var sessionUniqueId= myArrayVar.Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType=myArrayVar.Combiner[j].type;
alert(sessionType);
var sessionRule=myArrayVar.Combiner[j].rule;
alert(sessionRule);
}
}
Can anyone suggest a solution?
for (var i = 0; i < myArrayVar.length; i++) {
for (var j = 0; j < myArrayVar[i].Combiner.length; j++) {
var sessionUniqueId = myArrayVar[i].Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType = myArrayVar[i].Combiner[j].type;
alert(sessionType);
var sessionRule = myArrayVar[i].Combiner[j].rule;
alert(sessionRule);
}
}
You never use i. You need it to access the current array element, for example:
for(var j=0; j<=myArrayVar[i].Combiner.length; j++){
myArrayVar is your array, myArrayVar[i] is the i-th element in that array and myArrayVar[i].Combiner is the combiner (array) property of the i-th element.
You'll make it yourself a lot easier if you give the current element a name as well. (You probably want to come up with a less generic name such as current though.)
for(var i=0; i<myArrayVar.length;i++){
var current=myArrayVar[i];
for(var j=0; j<current.Combiner.length; j++){
var sessionUniqueId=current.Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType=current.Combiner[j].type;
alert(sessionType);
var sessionRule=current.Combiner[j].rule;
alert(sessionRule);
}
}
Also, i cannot equal myArrayVar.length as that index is already out of bounds. Your loop condition should have < instead of <=.
You have an array with one element. That element is in myArrayVar[0] and it is an object. To iterate over the object use a for ... in loop.
var myObj = myArrayVar[0];
for(var key in myObj){
var value = myObj[key];
console.log(key, value);
}
You should also use console.log for debugging. It will show you more information about objects than alert can.
Try using "<" instead of "<=" in the for loops, and "myArrayVar[i].Combiner" instead of "myArrayVar.Combiner".
There are a couple of problems I see. First, your i and j variables go one spot too far. They should be using < instead of <=.
Secondly, you're declaring variables inside the loop. That's fine, but JavaScript isn't block scoped, so you really end up with the same three variables overwriting each other as many times as there are items in the list. Your example data only has one item so you probably won't notice the overwriting problem just yet–but once you have multiple items in the list it could be a problem.

for loop using knockout js view.items()

I am using the below code to iterated through the items list,
alert(view.items().length);
for(var i=0; i < view.items().length; i++){
alert(view.items(i).productStatus);
}
I am getting an undefined error. Am i missing some thing??
You should access the array as view.items()[i].productStatus.
Assuming items is an observable array.
for(var i=0; i < view.items().length; i++){
alert(view.items()[i].productStatus);
}

Building Array in forloop

I'm trying to create a basic for loop which creates an array but am a little confused in how to structure it... this is an example of the array:
var list = [
{id: "135", data: [9,129,345, 687]},
{id: "239", data: [596,382,0,687,33467]}
];
Those are just example numbers but i need to make it in a for loop (because the numbers come from variables, but i've got no idea how i do it =/
I know how to make a 1 dimensional array with a for loop but not anything this complex..
Does any one have an example loop to show how its structured?
EDIT: Just understood what you meant.
This is a bit of pseudo to show how you would create an array like the one in question
var list = [];
for(var i = 0; i < objectcount; i++){
// Here you need some way to get the ID for each should be dependant on 'i'
var obj = {id: 10, data: []}; object
for(var j = 0; j < datacount; j++){
// You need some way to retrieve each data number, dependent on 'j'
obj.data.push(somenumber)
}
list.push(obj)
}
OLD ANSWER
Assuming that you want to create an array of all the data arrays inside each object try something like this:
var newarray = [];
// This will iterate through each object in the list array.
for(var i = 0; i < list.length; i++){
// This will iterate though each value in the data array
// of the current list object
for(var j = 0; j < list[i].data.length; j++){
// Then you add that value to 'newarray'
newarray.push(list[i].data[j]);
}
}
Not sure if this is what you're asking, but to access the list object as shown you could
alert(list[0].id);
alert(list[0].data[0]);
and you would get 135 and 9 respectively.
Here's the for loops to see them all:
for (i=0; i<list.length; i++) {
alert (list[i].id);
for (j=0; j<list[i].data.length; j++) {
alert (list[i].data[j]);
}
}

Categories