I'm new to javascript and still learning them.
So I was building a project where I want to display a multiple object, which I put it in an array, to the DOM.
I am not sure what method to use to access the object inside the array.
<div class="container">
<div class="hero">
<h2>List of Names</h2>
</div>
<ul class="name-list"></ul>
</div>
This is my js file:
const nameList = document.querySelector('.name-list');
//List of Names
const john = {
name: 'john',
car: 'fiat',
address: 'new york'
}
const mike = {
name: 'mike',
car: 'toyota',
address: 'sydney'
}
const greg = {
name: 'greg',
car: 'nissan',
address: 'melbourne'
}
//Store list of names in an array
const allNames = [
john,
mike,
greg
]
function displayName (){
//Not sure what methods to use to
return `
<li>
<p>Name: ${allNames.name}</p>
<p>Car: ${allNames.car}</p>
<p>Address: ${allNames.address}</p>
</li>
`
}
So I kind of want to display all the objects in the DOM.
Is it necessary to put the objects in the array first? What methods do I use to return a list in the file? Or do you know any easier methods to display all the objects in the DOM?
Thank you so much for the help.
Maybe you can try something like this :
function showNameList() {
const allNames = [
{
name: 'john',
car: 'fiat',
address: 'new york'
},
{
name: 'mike',
car: 'toyota',
address: 'sydney'
},
{
name: 'greg',
car: 'nissan',
address: 'melbourne'
}
]
var namelist = allNames.map(function (t, i) {
return `<b>Name : </b> ${t.name}<br/><b>Car : </b> ${t.car}<br/><b>Address : </b> ${t.address}<br/><br/>`;
})
document.getElementById('name-list').innerHTML =
'<li>' + namelist.join('</li><li>') + '</li>'
}
showNameList()
<div class="container">
<div class="hero">
<h2>List of Names</h2>
</div>
<ul id="name-list"></ul>
</div>
use map function to display them :
const values = allNames.map(item=>{
return(
<li>
<p>Name: ${item.name}</p>
<p>Car: ${item.car}</p>
<p>Address: ${item.address}</p>
</li>
)
})
<div class="container">
<div class="hero">
<h2>List of Names</h2>
</div>
<ul class="name-list">
{values}
</ul>
</div>
Related
I have a list of WebsiteOwners. I'm trying to build a UI which will display more information about the owners when I click on them.
this.toExpand = ko.observableArray(); //initialize an observable array
this.invertExpand = ko.observable("");
this.invertExpand = function (index) {
if (self.invertExpand[index] == false) {
self.invertExpand[index] = true;
alert(self.invertExpand[index]); //testing whether the value changed
}
else {
self.invertExpand[index] = false;
alert(self.invertExpand[index]); //testing whether the value changed
}
};
Here's the HTML code :
<div data-bind="foreach: WebsiteOwners">
<div>
<button data-bind="click: $root.invertExpand.bind(this,$index())" class="label label-default">>Click to Expand</button>
</div>
<div data-bind="visible: $root.toExpand()[$index]">
Primary Owner: <span data-bind="text:primaryOwner"></span>
Website Name : <span data-bind="text:websiteName"></span>
//...additional information
</div>
</div>
You can store one of your WebsiteOwner items directly in your observable. No need to use an index.
Don't forget you read an observable by calling it without arguments (e.g. self.invertExpand()) and you write to it by calling with a value (e.g. self.invertExpand(true))
I've included 3 examples in this answer:
One that allows only a single detail to be opened using knockout
One that allows all details to be opened and closed independently using knockout
One that does not use knockout but uses plain HTML instead 🙂
1. Accordion
Here's an example for a list that supports a single expanded element:
const websiteOwners = [
{ name: "Jane", role: "Admin" },
{ name: "Sarah", role: "Employee" },
{ name: "Hank", role: "Employee" }
];
const selectedOwner = ko.observable(null);
const isSelected = owner => selectedOwner() === owner;
const toggleSelect = owner => {
selectedOwner(
isSelected(owner) ? null : owner
);
}
ko.applyBindings({ websiteOwners, isSelected, toggleSelect });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: { data: websiteOwners, as: 'owner' }">
<li>
<span data-bind="text: name"></span>
<button data-bind="
click: toggleSelect,
text: isSelected(owner) ? 'collapse' : 'expand'"></button>
<div data-bind="
visible: isSelected(owner),
text: role"></div>
</li>
</ul>
2. Independent
If you want each of them to be able to expand/collapse independently, I suggest adding that state to an owner viewmodel:
const websiteOwners = [
{ name: "Jane", role: "Admin" },
{ name: "Sarah", role: "Employee" },
{ name: "Hank", role: "Employee" }
];
const OwnerVM = owner => ({
...owner,
isSelected: ko.observable(null),
toggleSelect: self => self.isSelected(!self.isSelected())
});
ko.applyBindings({ websiteOwners: websiteOwners.map(OwnerVM) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: websiteOwners">
<li>
<span data-bind="text: name"></span>
<button data-bind="
click: toggleSelect,
text: isSelected() ? 'collapse' : 'expand'"></button>
<div data-bind="
visible: isSelected,
text: role"></div>
</li>
</ul>
3. Using <details>
This one leverages the power of the <details> element. It's probably more accessible and by far easier to implement!
const websiteOwners = [
{ name: "Jane", role: "Admin" },
{ name: "Sarah", role: "Employee" },
{ name: "Hank", role: "Employee" }
];
ko.applyBindings({ websiteOwners });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: websiteOwners">
<li>
<details>
<summary data-bind="text: name"></summary>
<div data-bind="text: role"></div>
</details>
</li>
</ul>
I am having difficulty to get all the array of objects and display it into HTML lists. Can anyone help me, please. The below is my HTML and JavaScript code. Looking forward to your help.
const allData = [{
date: '2nd',
venue: 'venue1',
location: 'location1',
},
{
date: '3rd',
venue: 'venue2',
location: 'location2',
},
{
date: '4th',
venue: 'venue3',
location: 'location3',
}
]
allData.forEach(data => {
[...document.querySelectorAll('.targets')].forEach(list => {
list.innerHTML = `
<h5 >DATE</h5>
<h4 >${data.date}</h4>
<h5 >VENUE</h5>
<h4 >${data.venue}</h4>
<h5 >LOCATION</h5>
<h4 >${data.location}</h4>
<Button >BUY TICKETS</Button>
`;
})
});
<ul>
<li class="targets"></li>
</ul>
If you change the order of for loops execution and append each string to the previous it works!
const allData = [{
date: '2nd',
venue: 'venue1',
location: 'location1',
},
{
date: '3rd',
venue: 'venue2',
location: 'location2',
},
{
date: '4th',
venue: 'venue3',
location: 'location3',
},
];
const list = document.querySelector('.target')
let innerHTML = '';
allData.forEach(data => {
innerHTML += `
<li>
<h5 class = "shows__date">DATE</h5>
<h4 class = "shows__calander">${data.date}</h4>
<h5 class = "shows__venue-title">VENUE</h5>
<h4 class = "shows__venue">${data.venue}</h4>
<h5 class = "shows__location-title">LOCATION</h5>
<h4 class = "shows__location">${data.location}</h4>
<Button Class = "shows__btn">BUY TICKETS</Button>
</li>
`;
});
list.innerHTML = innerHTML;
<ul class="target">
</ul>
I think you don't need to loop for class='targets' because you only have one li in your html code. It might be better to just get the ul element and then loop allData variable, then change the ul innerHTML on each loop.
HTML Code
<ul></ul>
JS Code:
const allData= [
{
date: '2nd',
venue: 'venue1',
location: 'location1',
},
{
date: '3rd',
venue: 'venue2',
location: 'location2',
},
{
date: '4th',
venue: 'venue3',
location: 'location3',
},
]
let ul = document.querySelector('ul')
let listContent = ''
allData.forEach(data=>{
listContent = listContent +
`
<li>
<h5 >DATE</h5>
<h4 >${data.date}</h4>
<h5 >VENUE</h5>
<h4 >${data.venue}</h4>
<h5 >LOCATION</h5>
<h4 >${data.location}</h4>
<Button >BUY TICKETS</Button>
</li>
`;
});
ul.innerHTML = listContent
Edited based on pilchard comment
The OP provides a basic list structure by the "naked" <ul/> / <li/>
markup.
Thus, there is only a sole <li class="targets"></li> element which can be accessed with a query like '.targets'. Which means, the OP always writes to one and the same element which shows the expected result of a list which features just one element with the data-array's last item-data.
But the <li/> element can be used as a blueprint for creating other list-item elements via <node>.cloneNode which all will be <li class="targets"></li>-alike.
Now one can assign the correct data-item related html content to each newly created list-item clone which also gets appended to its parent list-element ...
const allData = [{
date: '2nd',
venue: 'venue1',
location: 'location1',
}, {
date: '3rd',
venue: 'venue2',
location: 'location2',
}, {
date: '4th',
venue: 'venue3',
location: 'location3',
}];
const venueItemBlueprint = document.querySelector('li.targets');
const venueList = venueItemBlueprint && venueItemBlueprint.parentElement;
if (venueList) {
venueList.innerHTML = '';
allData.forEach(venueData => {
const venueItem = venueItemBlueprint.cloneNode();
venueItem.innerHTML = `
<h5>DATE</h5>
<h4>${ venueData.date }</h4>
<h5>VENUE</h5>
<h4>${ venueData.venue }</h4>
<h5>LOCATION</h5>
<h4>${ venueData.location }</h4>
<Button>BUY TICKETS</Button>`;
venueList.appendChild(venueItem);
});
}
<ul>
<li class="targets"></li>
</ul>
I'm developing a simple SPA framework. I have a problem. I want to render my Obj data in HTML. Below is my code and my online example
var data = {
for: {
animal: [{
name: 'dog',
alive: 'false'
},
{
name: 'cat',
alive: 'true'
}
],
human: [{
name: 'bob',
sex: 'male'
},
{
name: 'alice',
sex: 'female'
}
]
}
};
<html>
<div id="app">
<ol>
<li np-for="animal">
<np tag="text-for" data="name"></np><br>
<np tag="text-for" data="alive"></np>
</li>
</ol>
</div>
</html>
best way to solve it?
If you are not using a framework, then I suggest you using jQuery, so the full code looks like this
let data = {
animals : [
{ name: 'dog', alive : 'false'},
{ name: 'cat', alive : 'true'}
]
};
let animalList = $('#animals');
data.animals.forEach(function(data) {
animalList.append(`<li>
<b>${data.name}</b>
<i>${data.alive}</i>
</li>`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<div id="app">
<ul id="animals">
<!-- data will automatically generated by jQuery -->
</ul>
</div>
</html>
I suggest you to using let or const for static variable instead of var, read more var vs let vs const in JavaScript
Read more about jQuery
I'm trying to group the items in a ng-repeat using a condition.
An example condition is to group all elements with the same hour.
The data:
[
{name: 'AAA', time: '12:05'},
{name: 'BBB', time: '12:10'},
{name: 'CCC', time: '13:20'},
{name: 'DDD', time: '13:30'},
{name: 'EEE', time: '13:40'},
...
]
The 'time' field is actually a timestamp (1399372207) but with the exact time the example output is easier to understand.
I am listing these items using ng-repeat:
<div ng-repeat="r in data| orderBy:sort:direction">
<p>{{r.name}}</p>
</div>
also tried with:
<div ng-repeat-start="r in data| orderBy:sort:direction"></div>
<p>{{r.name}}</p>
<div ng-repeat-end></div>
A valid output is:
<div class="group-class">
<div><p>AAA</p></div>
<div><p>BBB</p></div>
</div>
<div class="group-class">
<div><p>CCC</p></div>
<div><p>DDD</p></div>
<div><p>EEE</p></div>
</div>
My last option if there isn't a simple solution for my problem would be to group the data and then assign it to the scope variable used in ng-repeat.
Any thoughts?
You can use groupBy filter of angular.filter module.
so you can do something like this:
usage: collection | groupBy:property
use nested property with dot notation: property.nested_property
JS:
$scope.players = [
{name: 'Gene', team: 'alpha'},
{name: 'George', team: 'beta'},
{name: 'Steve', team: 'gamma'},
{name: 'Paula', team: 'beta'},
{name: 'Scruath', team: 'gamma'}
];
HTML:
<ul ng-repeat="(key, value) in players | groupBy: 'team'">
Group name: {{ key }}
<li ng-repeat="player in value">
player: {{ player.name }}
</li>
</ul>
RESULT:
Group name: alpha
* player: Gene
Group name: beta
* player: George
* player: Paula
Group name: gamma
* player: Steve
* player: Scruath
UPDATE: jsbin
First make group in Controller:
$scope.getGroups = function () {
var groupArray = [];
angular.forEach($scope.data, function (item, idx) {
if (groupArray.indexOf(parseInt(item.time)) == -1) {
groupArray.push(parseInt(item.time));
}
});
return groupArray.sort();
};
Then Make a Filter for it:
myApp.filter('groupby', function(){
return function(items,group){
return items.filter(function(element, index, array) {
return parseInt(element.time)==group;
});
}
}) ;
Then Change Template:
<div ng-repeat='group in getGroups()'>
<div ng-repeat="r in data | groupby:group" class="group-class">
<div><p>{{r.name}}</p></div>
</div>
</div>
SEE DEMO
Just a simple HTML solution for static groups.
<ul>
Group name: Football
<li ng-repeat="player in players" ng-if="player.group == 'football'">
Player Name: {{ player.name }}
</li>
Group name: Basketball
<li ng-repeat="player in players" ng-if="player.group == 'basketball'">
Player Name: {{ player.name }}
</li>
</ul>
Output:
Group name: Football
- Player Name: Nikodem
- Player Name: Lambert
Group name: Basketball
- Player Name: John
- Player Name: Izaäk
- Player Name: Dionisia
I am trying to display descendant elements in array using "with" binding.
But it displays only last items in "exercises" and I want to see all of them. How is it possible to fix this?
And after that, how can I make each item in array editable?
My ViewModel:
function AppViewModel() {
var self = this;
self.workouts = ko.observableArray([
{name: "Workout1", exercises:{
name: "Exercise1.1",
name: "Exercise1.2",
name: "Exercise1.3"
}},
{name: "Workout2", exercises:{
name: "Exercise2.1",
name: "Exercise2.2",
name: "Exercise2.3"
}},
{name: "Workout3", exercises:{
name: "Exercise3.1",
name: "Exercise3.2",
name: "Exercise3.3"
}},
{name: "Workout4", exercises:{
name: "Exercise3.1",
name: "Exercise3.2",
name: "Exercise3.3"
}},
]);
self.removeWorkout = function() {
self.workouts.remove(this);
};
}
ko.applyBindings(new AppViewModel());
The View:
<div class="content">
<ul data-bind="foreach: workouts">
<li>
<span data-bind="text: name"> </span>
Remove
<ul data-bind="with: exercises">
<li data-bind="text: name"></li>
</ul>
</li>
</ul>
</div>
Here's this code at jsfiddle:
http://jsfiddle.net/9TrbE/
Thanks!
The exercises property you declared as an object should be an array.
self.workouts = ko.observableArray([
{name: "Workout1", exercises:[
{ name: "Exercise1.1" },
{ name: "Exercise1.2" },
{ name: "Exercise1.3" }
]},
]);
So you can use this view :
<div class="content">
<ul data-bind="foreach: workouts">
<li>
<span data-bind="text: name"> </span>
Remove
<ul data-bind="foreach: exercises">
<li data-bind="text: name"></li>
</ul>
</li>
</ul>
</div>
Declaring :
var exercises = {
name: "Exercise1.1",
name: "Exercise1.2",
name: "Exercise1.3"
};
Is like doing that :
var exercises = {
name: "Exercise1.1",
};
exercises.name: "Exercise1.2";
exercises.name: "Exercise1.3";
Get it with this
Here's this code at jsfiddle
self.workouts = ko.observableArray([
{name: "Workout1", exercises:[
{ name: "Exercise1.1" },
{ name: "Exercise1.2" },
{ name: "Exercise1.3" }
]},
]);
`http://jsfiddle.net/9TrbE/8/