reading array json with javascript - javascript

I have this array tv, when I read this array with a loop for, it just give me the last item, in this case Toshiba,
how can I do to it show me the TV brands??
for (var i=0;i<tv.length;i++){
$('#item').html(tv[i].Brand)}
<div id='item'></div>
Array tv:
var tv = [{"Name":"TV","Brand":"Samsung"},
{"Name":"TV","Brand":"Toshiba"},
{"Name":"TV","Brand":"LG"}]

html() overwrites the content on each iteration, that's why only the last one is visible, the others are overwritten. You should be using append:
$('#item').empty();
for (var i=0; i<tv.length; i++){
$('#item').append(tv[i].Brand);
}

The problem: You have only one div#item element and you are updating its value in every iteration.
Solution: Dynamically create and append an element to show each item in the array like:
for (var i=0;i<tv.length;i++){
$('<div/>').addClass('item').html(tv[i].Brand).appendTo('.container');
}
where:
item is a class - now that you have multiple elements
container - assumed to the parent element under which you want the items displayed

Related

Change innerText of HTML list items from console with JavaScript

I am new to programming and I have been looking for solutions, but what I find are more complciated solutions than it should be and I am being asked.
I have this HTML
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <meta content="utf-8" http-equiv="encoding">
 </head>
 <body>
  <h3>Pizza toppings:</h3>
  <ul id="ingredients">
   <li>Batsilica</li>
   <li>Tomtato</li>
   <li>Morezarella</li>
   <li>Hams</li>
  </ul>
 </body>
</html>
So I have to change the ingredients with the console.
I wrote this so I get printed the list:
let toppings = document.querySelectorAll('#pizza-toppings li');
for (let i = 0; i < ingredients.length; i++) {
console.log(ingredients[i].innerText);
}
I dont know how to modify those items of the list one by one. It shouldnt be any replaceChild nor change the list completely, but selecting them and "modifying them".
maybe I get the children list of the element with qSelector but still dont know how to correct the spelling of those. It is not like I can right click in the printed list and edit it.
Help? Thanks
Infact we use # to select an id, so you need to put your list's id which is ingredients. And your array of matching items is called toppings, so you need to set your loop limit to toppings.length.
Although i would recommend using map instead of for loop
let toppings = document.querySelectorAll('#ingredients li');
for (let i = 0; i < toppings.length; i++) {
console.log(toppings[i].innerText);
}
This should display all of your items on the console. But if you want to edit item, for example you want to change "Tomtato" into "Meat" you have to do
toppings[1].innerText="Meat"
you don't have any element #pizza-toppings in document. So, toppings is empty node list. ingredients is object, not array of li elements. If you want iterate over li try this:
let ingredients = document.querySelectorAll('#ingredients li');
for (let i = 0; i < ingredients.length; i++) {
console.log(ingredients[i].innerText); }
}
One way to grab all of the list items and then modify them (provided you want to perform the same operation on all of the li's) would be to put them in an array:
let ingredients = document.getElementById("ingredients").getElementsByTagName("li");
//create empty array:
let ingredients_list = []
//create loop to iterate over every li:
for (let i = 0; i < ingredients.length; i++) {
//create variable to grab the text from each <li>:
let ingredients_text = ingredients[i].innerText;
//add the text from each li to the ingredients_list array:
ingredients_list.push(ingredients_text);
}
// you will now have all of your li's in an array where you can manipulate them as you wish using any array methods. For example, lets convert all of the text to uppercase and then log it to the console using the forEach array method:
ingredients_list.forEach(element => console.log(element.toUpperCase()))
//returns:
"HAMS"
"BATSILICA"
"TOMTATO"
"MOREZARELLA"
The above is just a basic example of how you can manipulate a list that has been converted into an array using the forEach method.
Another basic example would be to return all the items from the array in a single string using the join method:
console.log(ingredients_list.join(" "))
You can see a full list of available methods at the following link on the left navbar:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
I'm not sure what you want to do exactly with the list items (the original question is not 100% clear) but hopefully this points you in the right direction.

Angular Sorting and counting, Dragula

I have the following scenario:
A JSON object array gets fetched with angular ajax and displayed as list with ng-repeat.
The list gets sorted by object property "index", which is set as default input value of the respective list item.
The user can change the input values.
On press of a button, the list gets redrawn, sorted by the updated input values.
Now there should be a counter, ++ whenever a list item changes position.
I so far managed to count all list items with updated values.
How do I register position changes for the other list items that change position?
For example: #3 changes position to #1, then #1 and #2 also change position.
Second, using Dragula, the list items are now draggable.
How can I resort the list after list items were dragged?
I also tired Angular Dragula without success.
here is my code on github.
Thank you for your help!
I had a similar issue. You need a way of getting the DOM indexing and updating the JavaScript object to match. I looped through the DOM elements, got their index values, found the corresponding item in the data object and then set the index value in the object to that of the DOM index value. Hope this example helps someone.
var updateIndexes = function() {
// this gets the index of any DOM element, like jQuery index()
function getIndex(el) {
for (var i = 0; el = el.previousElementSibling; i++);
return i;
}
// loop through the list DOM elements
for (var i = 0; i < dataArray.length; i++) {
var dataId = dataArray[i].id;
var domIndex = getIndex(document.getElementById(dataId));
dataArray[i].index= domIndex;
}
};

How to handle a select with multiple items when only one item is selected

I have a select form element and it accepts multiple items.
When the form is submitted I'm adding the items into an array to then handle them then running through the array to perform an action on each item.
I'm coming across a problem when only one item is selected.
The length of the array when one item is passed through is not 1 it's the number of characters in the item that is selected.
function processForm(formObject){
var list = [];
list = formObject.listElement;
for (var i=0;i<list.length;i++) {
Logger.log(list[i]);
}
}
The above would log each item if more than one item is selected in the form. If only one is selected the length is the number of character in that one item. How can I resolve this so if only one item is selected we treat this as an array with one item?
You have:
var list = [];
which assigns an empty array to list, then:
list = formObject.listElement
replaces it with whatever is returned by formObject.listElement, so the initial assignment is pointless.
You haven't indicated what type of control listElement is, it may be a Class MultipleChoiceItem or Class ListItem. Both have a getChoices method that returns an array of the choices.
If you use that method, there should be no need to test whether the return value is an array or not, it should always be a (possibly empty) array:
list = formObject.listElement.getChoices();
assuming that listElement is one of the above objects.
Iterating through a string as if it were an array would give the behavior you describe. You can convert an array first, if it's not already one
var list = formObject.listElement;
if (!Array.isArray(list)) list = [list];

JS Slice only removes Items when they were in the Constructor

I try to remove the first Item so that all other move up in an Array I create with
..
Queue: [],
..
and dynamically push Items into.
I later use slice to remove them and have then next Item be the first one.
..
thread.Queue.slice(0, 1);
..
It should return the first Item of the Array, which it does, but it should also remove it from the array and move all other up.
Here is a example which shows, that is neither working in the Browser. (I found this 'behaviour' in Node.js)
http://jsfiddle.net/bTrsE/
or rather
http://gyazo.com/b3dcdbf4f74642c04fe1c1025f225a08.png
Array.Slice = Is an implementation of SubArray, From an array you want to extract certain elements from the index and return a new array.
Example:
var cars = ['Nissan','Honda','Toyota'];
var bestCars = cars.splice(0,1);
console.log(bestCars);
//This should output Nissan Because i like Nissan
For your problem you should be looking Array.Splice(), splice adds / removes an element from the index
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
The .slice() method does not alter the original array. It returns a shallow copy of the portion of the array you asked for.

How to add key/value pair in to array dynamically

I want to add an array dynamically using jquery. How can i do that.(or)
I want to push the elements in to array like this.
var array = [{"question":"1","answer":"2"}];
i want to do that dynamically using for loop i mean
initially i will add
array.push({"question":"1"});
then array.push({"answer":"2"});
but I want the elements to in the same array[0] element
but it is taking as array[0],array[1]
How can I do that. I am using for loop to add the elements in to an array.
If you are pushing an answer immediately after, can you not do something like
array[index] = { "question" : array[index].question, "answer": 2 };
If not you will have to find some other way of finding the index where the question was pushed and then
Just note that array.push always adds a new object to the array, and does not update it.

Categories