how to create multiple bullets with the forEach function - javascript

var data = {
pets:[
{
type: "Dogs Breeds",
name: "Dog",
breed: ["Dalmation", "Poodle", "Shitzu"]
},
{
type: "Cats Breeds",
name:"Cat",
breed:["Ragdoll", "Scottish Fold", "Sphynx"]
},
{
type: "Rabbits Breeds",
name: "Rabbit",
breed: ["Holland Lop", "Rex", "Mini Lop"]
}
]
};
var content = document.getElementById("content")
data.pets.forEach(pets => {
let h1 = document.createElement("h1");
let h1text = document.createTextNode(pets.name);
h1.appendChild(h1text);
content.appendChild(h1);
let h2 = document.createElement("h2");
let h2text = document.createTextNode(pets.type);
h2.appendChild(h2text);
content.appendChild(h2);
let ul = document.createElement("ul")
let li = document.createElement("li");
let text = document.createTextNode(pets.breed);
li.appendChild(text);
ul.appendChild(li);
content.appendChild(ul);
})
This is my code and I need to results to come up as separate bullet points for the breed category. I'm pretty sure the the issue stems from the fact that the ul is in the forEach so each iteration only sees the breed line as one name. I'm not sure how to fix this please help!!

Is this the result you are looking for?
Nested Loop
You can do a nested looping (a .forEach() in another .forEach()) to loop through pets and loop through the breed in pets
var data = {
pets:[
{
type: "Dogs Breeds",
name: "Dog",
breed: ["Dalmation", "Poodle", "Shitzu"]
},
{
type: "Cats Breeds",
name:"Cat",
breed:["Ragdoll", "Scottish Fold", "Sphynx"]
},
{
type: "Rabbits Breeds",
name: "Rabbit",
breed: ["Holland Lop", "Rex", "Mini Lop"]
}
]
};
var content = document.getElementById("content")
data.pets.forEach(pets => {
let h1 = document.createElement("h1");
let h1text = document.createTextNode(pets.name);
h1.appendChild(h1text);
content.appendChild(h1);
let h2 = document.createElement("h2");
let h2text = document.createTextNode(pets.type);
h2.appendChild(h2text);
content.appendChild(h2);
let ul = document.createElement("ul")
pets.breed.forEach(val=>{
let li = document.createElement("li");
let text = document.createTextNode(val);
li.appendChild(text);
ul.appendChild(li);
})
content.appendChild(ul);
})
<div id="content"></div>

Related

How can I add items in arraylist from a function? (JavaScript)

I have this function and I want to add this items in my arraylist. I know data.push(...) is not correct, so what it's the correct way?
function addinfo(data) {
var id = document.getElementById("courseid").value;
var nm = document.getElementById("name").value;
var yr = document.getElementById("year").value;
var syll = document.getElementById("syllabus").value;
var sem = document.getElementById("semester").value;
var teach = document.getElementById("teaching").value;
data.push(id,nm,yr,syll,sem,teach);
}
var data = [
{
courseid: "1",
name: "Artificial Intelligence",
year: "2021",
syllabus: "3",
semester: "2",
teaching: "Johan"
}
]
I assume you want to push all these values as an object into the data array. You could achieve that by doing the following.
By giving the variables the same name as the keys in the object you can leave that out.
var data = [
{
courseid: "1",
name: "Artificial Intelligence",
year: "2021",
syllabus: "3",
semester: "2",
teaching: "Johan"
}
]
function addinfo(data) {
var courseid = document.getElementById("courseid").value;
var name = document.getElementById("name").value;
var year = document.getElementById("year").value;
var syllabus = document.getElementById("syllabus").value;
var semester = document.getElementById("semester").value;
var teaching = document.getElementById("teaching").value;
data.push({courseid,name,year,syllabus,semester,teaching});
}
Try this:
function addinfo(data) {
data.push({
courseid: document.getElementById("courseid").value,
name: document.getElementById("name").value,
year: document.getElementById("year").value,
syllabus: document.getElementById("syllabus").value,
semester: document.getElementById("semester").value,
teaching: document.getElementById("teaching").value
});
}
Maybe you can use a function that adds according to element ids stored in an array. Errors are not handled.
const fields = ["courseid", "name", "year", "syllabus", "semester", "teaching"];
function addinfo(anyFieldList, data) {
const dataItem = {};
for (let aField of anyFieldList){
dataItem[aField] = document.getElementById(aField).value;
}
data.push(dataItem);
}
let data = [
{
courseid: "1",
name: "Artificial Intelligence",
year: "2021",
syllabus: "3",
semester: "2",
teaching: "Johan"
}
]

Creating Objects with name values from Array

I have an array such as var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"]; and I would like to be able to loop through the array to create an object from each element.
var zoo = {
Dog : {
color: brown,
age: 4
},
Cat : {
color: black,
age: 12
I have found some solutions for defining the other properties with .keys and .values but I am stuck on how to name the object. Thanks for any help!
You can achieve the solution using Array.reduce.
reduce provides an elegant way to return desired output based on your array.
var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var zoo=arr.reduce((zooObj, animal)=>
{
zooObj[animal] = {
color: 'black', //You can add color based on some logic here
age: 4 //You can add age based on some logic here
}
return zooObj
}, {})
console.log(zoo) //*Output*: { "Dog": { "color": "black", "age": 4 }, "Cat": { "color": "black", "age": 4 }, "Horse": { "color": "black", "age": 4 }, "Pig": { "color": "black", "age": 4 }, "Cow": { "color": "black", "age": 4 } }
You can try with below:
var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var colors = ["Red", "Blue", "Green", "Dark", "Yellow"];
var zoo={};
var i = 10;
var colorIndex = 0;
arr.forEach(v=>{
zoo[v]={};
zoo[v].age=i++;
zoo[v].color=colors[colorIndex++];
});
console.log(zoo);
You can simply do it in this way :
var objArr = {};
arr.forEach((data, index) => {
objArr[data] = data; //here you can add what ever value you want to add to that key
})
var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var zoo = {};
for (var i of arr ){
zoo[i] = {};
zoo[i].age = 'age'; //fill the age
zoo[i].color= 'your favorite color'; //fill with your favorite color
}
console.log(zoo);
This will do-
var animal = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var color=["red","green","blue","orange","yellow"];
var age=[2,5,8,6,23];
var obj={};
animal.forEach((e)=>{
obj[e]={};
obj[e].age=age[animal.indexOf(e)];
obj[e].color=color[animal.indexOf(e)];
})
console.log(obj)
You can do this by using below logic.
Here define color and age array and inside loop store this dynamically.
var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var colors = ["brown","blak","white","red","gray"];
var ages = ["4","12","5","10","15"];
arr2 = {}
for(var i=0;i<arr.length;i++){
arr2[arr[i]] = {};
arr2[arr[i]].color = colors[i]; //fill the age
arr2[arr[i]].age= ages[i];
}
console.log(arr2);
https://jsfiddle.net/brahmpragya/w76xjm5y/29/

Building nested lists from ancestor data?

Given the structure:
{
id: 'id-1',
name: 'name1',
ancestors: []
},{
id: 'id-2',
name: 'name2',
ancestors: []
},{
id: 'id-3',
name: 'name3',
ancestors: ['id-1']
},{
id: 'id-4',
name: 'name4',
ancestors: ['id-3', 'id-1']
}
Assume they are not sorted in any meaningful way.
The ancestors field is an array showing the path up to top level.
What would be the most efficient way to build nested lists (ul)?
My first thought is a recursive approach, but that seems troublesome as it would repeatedly search the entire list. Since this will be a javascript solution running in the browser that could be problematic.
You could build a tree and then render a nested list.
function getTree(data) {
var o = {};
data.forEach(function (a) {
var parent = a.ancestors[0];
if (o[a.id] && o[a.id].children) {
a.children = o[a.id].children;
}
o[a.id] = a;
o[parent] = o[parent] || {};
o[parent].children = o[parent].children || [];
o[parent].children.push(a);
});
return o.undefined.children;
}
function buildList(tree, target) {
var ul = document.createElement('ul');
tree.forEach(o => {
var li = document.createElement('li');
li.appendChild(document.createTextNode(o.name));
buildList(o.children || [], li);
ul.appendChild(li);
});
target.appendChild(ul);
}
var data = [{ id: 'id-1', name: 'name1', ancestors: [] }, { id: 'id-2', name: 'name2', ancestors: [] }, { id: 'id-3', name: 'name3', ancestors: ['id-1'] }, { id: 'id-4', name: 'name4', ancestors: ['id-3', 'id-1'] }],
tree = getTree(data);
console.log(tree);
buildList(tree, document.body);
Build up a Map for faster lookup:
const byId = new Map(array.map(el => ([el.id, el]));
Then its pretty simple to create a nested tree, we just check if a node has no ancestors, then its a root element, otherwise we add it as a children of the parent:
const root = [];
for(const obj of array) {
if(obj.ancestors.length) {
const parent = byId.get(obj.ancestors[0]);
if(parent.children) {
parent.children.push(obj);
} else {
parent.children = [obj];
}
} else {
root.push(obj);
}
}
So now root contains a nested tree, you can use a recursive approach to traverse it:
function traverse(elements) {
for(const el of elements) {
// Render ...
traverse(el.children || []);
}
}
traverse(root);

Categorize object in JavaScript loop

I have the following object:
var object = [
{
"category": "Apple",
"color": "green"
},
{
"category": "Orange",
"color": "Orange"
},
{
"category": "Apple",
"color": "green"
}
];
I am trying to iterate the data via category, so the following would show in a list:
Apple
Apple
Orange
Below is the code I've tried but unfortuantely it shows in the order it appears in the object. Any ideas would be much appreciated.
function makeUL(object) {
var list = document.createElement('ul');
for(var i = 0; i < object.length; i++) {
var item = document.createElement('li');
var a = document.createElement("a");
a.textContent = object[i].category;
a.setAttribute('href', 'http://test');
item.appendChild(a);
list.appendChild(item);
}
return list;
}
A solution with group change:
var object = [{ "category": "Apple", "color": "green" }, { "category": "Orange", "color": "Orange" }, { "category": "Apple", "color": "green" }];
function makeUL(object) {
var div = document.createElement('div');
object.sort(function (a, b) { return a.category.localeCompare(b.category); });
object.forEach(function (aa) {
var a = document.createElement("a"),
item = document.createElement('li'),
p;
if (aa.category !== this.last) {
p = document.createElement('p');
p.innerHTML = aa.category;
div.appendChild(p);
this.list = document.createElement('ul');
div.appendChild(this.list);
this.last = aa.category;
}
a.textContent = aa.category;
a.setAttribute('href', 'http://test');
item.appendChild(a);
this.list.appendChild(item);
}, { last: undefined, list: undefined });
return div;
}
document.body.appendChild(makeUL(object));
You could use Array.sort
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}
sort the array before using it in for loop
object.sort(function(a,b){
return a.category > b.category
});
object.sort(function(a, b) {
return a.category > b.category;
});
Result
[ { category: 'Apple', color: 'green' },
{ category: 'Apple', color: 'green' },
{ category: 'Orange', color: 'Orange' } ]
If you want your array to be sorted alphabetically ( DESC order, from A to Z ) you have to call the .sort() method first
function makeUL(object) {
var list = document.createElement('ul');
object.sort();
for(var i = 0; i < object.length; i++) {
var item = document.createElement('li');
var a = document.createElement("a");
while(i<length - 1 && object[i].category == object[i+1].category)
a.textContent += object[i].color + ", ";
a.setAttribute('href', 'http://test');
item.appendChild(a);
list.appendChild(item);
}
return list;
}

add options to drop down list with javascript

I need to add options to a drop down list. I have an array with the options that I need in the drop down list, but I'm not sure how to append the array to the list
var productList = document.getElementById("selectFood");
var foodOption = document.createElement("option");
foodOption.textContent = [{
option1: "Meat Lovers"
}, {
option2: "Buffalo Wings"
}, {
option3: "margherita"
}, {
option4: "classic"
}];
for (i = 0; i < productList.length; i++) {
productList.appendChild(foodOption);
}
you can do with jquery,
$.each(foodOption.textContent, function (i, value) {
$('#selectFood').append($('<option>').text(value).attr('value',value));
});
You need to create an option element.
for (i = 0; i < foodOption.textContent.length; i++) {
var newElement = document.createElement('option');
newElement.innerHTML = foodOption.textContent[i];
productList.appendChild(newElement);
}
You have to make an array of string rather than array of objects
try this
foodOption.textContent = ["Meat Lovers" , "Buffalo Wings" , "margherita", "classic" ]
$.each(foodOption.textContent, function (index, value) {
$('#selectFood').append($('<option/>', { value: value, text: value }));
});
Try below code for your solution.
var productList = document.getElementById("selectFood");
var textContent = [{
option1: "Meat Lovers"
}, {
option2: "Buffalo Wings"
}, {
option3: "margherita"
}, {
option4: "classic"
}];
for(var iIntex in textContent) {
var foodOption = document.createElement("option");
var option=textContent[iIndex]["option"+(iIndex+1)];
foodOption.setAttribute("value",option);
foodOption.innerHTML=option;
productList.appendChild(foodOption);
}

Categories