How do I iterate through all the id's? - javascript

Check out the api --> https://api.icndb.com/jokes/random/10
Everytime when the user clicks on a specific joke, it will be added to the favorite list.
To keep the code concise I will only show the function itself:
(function() {
"use strict";
const getJokesButton = document.getElementById('getData');
getJokesButton.addEventListener('click', getData);
loadLocalStorage();
function loadLocalStorage() {
let storage = JSON.parse(localStorage.getItem('favoList')) || [];
let listOfFavorites = document.getElementById("favorites");
let emptyArray = '';
if(storage.length > 0) {
for(let i = 0; i < storage.length; i++) {
let idNumberJoke = storage[i].id;
emptyArray +=
`<li><input type="checkbox" id='${idNumberJoke}'/> User title: ${storage[i].joke}</li>`;
listOfFavorites.innerHTML = emptyArray;
}
} else {
return false;
}
}
// fetch data from api
function getData() {
let listOfJokes = document.getElementById("list-of-jokes");
fetch('https://api.icndb.com/jokes/random/10')
.then(function(res) {
return res.json();
}).then(function(data) {
// variable is undefined because it is not initialized. Therefore at some empty single quotes
let result = '';
console.log(data.value);
data.value.forEach((joke) => {
result +=
`<li><input type="checkbox" class='inputCheckbox' id='${joke.id}'/> User title : ${joke.joke}</li>`;
listOfJokes.innerHTML = result;
});
bindCheckbox();
}).catch(function(err) {
console.log(err);
});
}
function clickedButton() {
getJokesButton.setAttribute('disabled', 'disabled');
getJokesButton.classList.add('opacity');
}
function bindCheckbox() {
let inputCheckbox = document.querySelectorAll('input[type=checkbox]');
let elems = document.getElementById('list-of-jokes').childNodes;
let favoriteList = document.getElementById('favorites');
let fav = JSON.parse(localStorage.getItem('favoList'))|| [];
if(elems.length > 0) {
inputCheckbox.forEach(function(element, index) {
inputCheckbox[index].addEventListener('change', function() {
let joke = this;
if(joke.checked && joke.parentNode.parentNode.id === 'list-of-jokes') {
joke.checked = false;
favoriteList.appendChild(joke.parentNode);
addFavorite(joke.id, joke.parentNode.innerText, fav);
}
if(joke.checked && joke.parentNode.parentNode.id === 'favorites') {
joke.checked = false;
removeFavorite(joke, index);
}
});
});
}
clickedButton();
}
function removeFavorite(favorite, index) {
let favoriteCheckBox = favorite;
let i = index;
// convert iterable object to an array, otherwise splice method would give an error.
let favoriteListItem = Array.from(favoriteCheckBox.parentNode);
favoriteListItem.splice(i, 1);
document.getElementById('list-of-jokes').appendChild(favorite.parentNode);
localStorage.setItem('favoList', JSON.stringify(favoriteListItem));
}
// store favorites in localStorage
function addFavorite(jokeId, jokeText, fav) {
let norrisJoke = {
id: jokeId,
joke: jokeText
};
let favorites = fav;
for (let i = 0; i < favorites.length; i++) {
if(favorites[i].id !== norrisJoke.id) {
favorites.push(norrisJoke);
}
}
// favorites[i].id !== norrisJoke.id
// always get the object before the push method and pass it into stringify
localStorage.setItem('favoList', JSON.stringify(favorites));
}
// function which will randomly add one joke to favorite list every 5 seconds
// function need a button which allows you to turn on and off this auto add function
})();
<div class="inner-body">
<button id="getData">GET Jokes</button>
<div class='inner-block'>
<h2>Chuck Norris Jokes</h2>
<ul class='unordered-list' id="list-of-jokes">
</ul>
</div>
<div class='inner-block'>
<h2>Favorites</h2>
<ul class='unordered-list' id="favorites">
</ul>
</div>
</div>
The keys and values would not be pushed into localStorage, the only thing I see is an empty [] in localStorage. The norrisJoke object literal will be dynamically changed. So how could I make this function works?
Too complex, but click on the link below and scroll down to the bottom:
https://codepen.io/chichichi/pen/Gyzzvb

You are trying to run through an empty list here
for (let i = 0; i < favorites.length; i++) {
if(favorites[i].id !== norrisJoke.id) {
favorites.push(norrisJoke);
}
}
This means that nothing will ever be pushed. You can reduce your list to an array of id, then check if the joke exists in the list.
const favIds = favorites.reduce((sum, element) => {
return sum.concat(element.id);
},
[]);
Now you can check if the joke doesn't exists in favorites
if(!favIds.includes(jokeId)){
favorites.push(norrisJoke);
}

The problem is the for loop, the first time it's executed favorites will be an empty array so it's length will be 0, so it will never enter the loop
Something like this should work:
favorites = favorites.filter(joke => joke.id !== norrisJoke.id).concat(norrisJoke);

let favorites = JSON.parse(localStorage.getItem('favoList'))|| {};
favorites[norrisJoke.id] =norrisJoke.joke
Why don't you use a map in place of an array?
Also as #fl9 points out your for loop will never start off! because favorites.length is 0 to begin with
But I want to check duplicates before the joke will be pushed into favorite list
By definition a hash will not allow duplicate entries, so no need to worry about duplications
Run localStorage.getItem('favoList') in the console of this fiddle :
(function() {
"use strict";
const getJokesButton = document.getElementById('getData');
getJokesButton.addEventListener('click', getData);
loadLocalStorage();
function loadLocalStorage() {
let storage = JSON.parse(localStorage.getItem('favoList')) || [];
let listOfFavorites = document.getElementById("favorites");
let emptyArray = '';
if(storage.length > 0) {
for(let i = 0; i < storage.length; i++) {
let idNumberJoke = storage[i].id;
emptyArray +=
`<li><input type="checkbox" id='${idNumberJoke}'/> User title: ${storage[i].joke}</li>`;
listOfFavorites.innerHTML = emptyArray;
}
} else {
return false;
}
}
// fetch data from api
function getData() {
let listOfJokes = document.getElementById("list-of-jokes");
fetch('https://api.icndb.com/jokes/random/10')
.then(function(res) {
return res.json();
}).then(function(data) {
// variable is undefined because it is not initialized. Therefore at some empty single quotes
let result = '';
console.log(data.value);
data.value.forEach((joke) => {
result +=
`<li><input type="checkbox" class='inputCheckbox' id='${joke.id}'/> User title : ${joke.joke}</li>`;
listOfJokes.innerHTML = result;
});
bindCheckbox();
}).catch(function(err) {
console.log(err);
});
}
function clickedButton() {
getJokesButton.setAttribute('disabled', 'disabled');
getJokesButton.classList.add('opacity');
}
function bindCheckbox() {
let inputCheckbox = document.querySelectorAll('input[type=checkbox]');
let elems = document.getElementById('list-of-jokes').childNodes;
let favoriteList = document.getElementById('favorites');
let fav = JSON.parse(localStorage.getItem('favoList'))|| [];
if(elems.length > 0) {
inputCheckbox.forEach(function(element, index) {
inputCheckbox[index].addEventListener('change', function() {
let joke = this;
if(joke.checked && joke.parentNode.parentNode.id === 'list-of-jokes') {
joke.checked = false;
favoriteList.appendChild(joke.parentNode);
addFavorite(joke.id, joke.parentNode.innerText, fav);
}
if(joke.checked && joke.parentNode.parentNode.id === 'favorites') {
joke.checked = false;
removeFavorite(joke, index);
}
});
});
}
clickedButton();
}
function removeFavorite(favorite, index) {
let favoriteCheckBox = favorite;
let i = index;
// convert iterable object to an array, otherwise splice method would give an error.
let favoriteListItem = Array.from(favoriteCheckBox.parentNode);
favoriteListItem.splice(i, 1);
document.getElementById('list-of-jokes').appendChild(favorite.parentNode);
localStorage.setItem('favoList', JSON.stringify(favoriteListItem));
}
// store favorites in localStorage
function addFavorite(jokeId, jokeText, fav) {
let norrisJoke = {
id: jokeId,
joke: jokeText
};
let favorites = fav;
for (let i = 0; i < favorites.length; i++) {
if(favorites[i].id !== norrisJoke.id) {
favorites.push(norrisJoke);
}
}
// favorites[i].id !== norrisJoke.id
// always get the object before the push method and pass it into stringify
localStorage.setItem('favoList', JSON.stringify(favorites));
}
// function which will randomly add one joke to favorite list every 5 seconds
// function need a button which allows you to turn on and off this auto add function
})();

Related

How can we use suiteScript(netsuite 2.0) in Node JS?

We need to get the field from the NetSuite Record page, i.e. workOrder.
I've created a single JS file that defines the pageInit function and where I'm getting the xyz field value.
I'd like to have the NetSuite xyz field locally in the console so I can use it in my Java-script code to make it dynamic.
But here, I am unable to get an exact solution for it.
How can we get the value of a netsuite (work-order page) form field using lambda and Node.js?
I don't see anything in your question that requires node so far. If you really need to use node you should look at the RESTlet/SuiteTalk options mentioned in the comments.
If you are wanting to run a script in the console the code below shows how to do that.
I keep a folder of these for various admin tasks. Just open a console and run when needed. The code below is fairly complex for one of these scripts (though not the most complex by far). It is used while editing a role. It presents a list of roles that have been set up with minimal permissions for a particular job function. The roles that are selected have their permissions applied to the currently being edited role.
N/currentRecord is the API that loads the current record's data.
require(['N/search', 'N/currentRecord', 'N/xml'], function(search, currentRecord, xml) {
const roleList = search.create({
type:'role',
filters:[
['custrecord_kotn_is_role_capabilities', 'is', 'T'], 'AND',
['isinactive', 'is', 'F']
],
columns:['name']
}).run().getRange({start:0, end:1000}).map(ref=>{
return {
id:ref.id,
name:ref.getValue({name:'name'})
};
}).map(r=>(`<option value=${r.id}>${r.name}</option>`)).join('\n');
console.log(roleList);
const body = document.querySelector('body');
const form=`
<div id="kotn-choose-roles" style="position:fixed;width:320px;left:50%;transform:translateX(-50%);top:30vh;background-color:white;border:1px solid #ccc;padding:10px;">
<form onSubmit="return false;">
<table><tr>
<td>Roles</td>
<td><select multiple id="kotn-roles-chosen">${roleList}</select>
</td>
</tr>
<tr><td colspan="2" align="center"><button id="kotn-apply-roles" type="button">Apply</button><button id="kotn-cancel-roles" type="button">Cancel</button>
</table>
</form>
</div>
`;
const frag = document.createElement('div');
frag.setAttribute('id', 'kotn-role-chooser');
frag.innerHTML = form;
body.appendChild(frag);
jQuery('#kotn-apply-roles').bind('click', function(){
const roleIds = jQuery('#kotn-roles-chosen').val();
console.log(roleIds);
applyRoles(roleIds);
alert('done');
frag.parentNode.removeChild(frag);
});
jQuery('#kotn-cancel-roles').bind('click', function(){
frag.parentNode.removeChild(frag);
});
function applyRoles(permSources){
const roleRec = currentRecord.get();
const machineNames = [
{
name:'custrecordmach',
permRef:'custrecord',
permLevelField:'permittedlevel',
restricted:'restriction'
},
{
name:'tranmach',
permRef: 'permkey1',
permLevelField:'permlevel1'
},
{
name:'listsmach',
permRef:'permkey3',
permLevelField:'permlevel3'
},
{
name:'setupmach',
permRef:'permkey4',
permLevelField:'permlevel4'
}
];
function doPerms(){
if(!permSources.length) return;
processPerm(permSources.shift()).then(doPerms);
}
function processPerm(id){
return fetchWithRetry(`/app/setup/role.nl?id=${id}&xml=T`,{
credentials: 'same-origin'
}).
then(resp =>{
console.log(id, resp.status);
return resp.text();
}).
then(data=>{
const roleDoc = xml.Parser.fromString({
text: data
});
console.log('role: ',selectValue(roleDoc, '/nsResponse/record/name'));
machineNames.forEach(m=>{
console.log('process machine', `//machine[#name="${m.name}"]/line`);
const docLines = xml.XPath.select({
node: roleDoc,
xpath: `//machine[#name="${m.name}"]/line`
});
console.log('machine lines', m.name, docLines.length);
const lines = docLines.map(line=>{
const perm = {
perm: selectValue(line, m.permRef),
level:parseInt(selectValue(line, m.permLevelField),10),
restricted:null
};
if(m.restricted){
perm.restricted = parseInt(selectValue(line, m.restricted), 10);
}
return perm;
});
console.log('lines for', m.name, lines);
const findPermIndex = perm =>{
for(var i = 0; i< lines.length; i++){
if(lines[i].perm == perm) return i;
}
return -1;
};
iter(roleRec, m.name, (idx, getV) =>{
const perm = getV(m.permRef);
const applyingIndex = findPermIndex(perm);
if(applyingIndex == -1) return;
const applyingPerm = lines.splice(applyingIndex, 1)[0];
console.log('have current perm', JSON.stringify(applyingPerm));
const permVal = getV(m.permLevelField);
const applyingLevel = (permVal >= applyingPerm.level) ? permVal : applyingPerm.level;
let applyingRestriction = null;
if(m.restricted){
let restrictionVal = parseInt(getV(m.restricted), 10) || null;
applyingRestriction = (!restrictionVal) ? null : applyingPerm.restricted;
if(restrictionVal && applyingRestriction){
if(applyingRestriction <restrictionVal){
applyingRestriction = restrictionVal;
}
}
}
setTimeout(()=>{
roleRec.selectLine({sublistId:m.name, line:idx});
roleRec.setCurrentSublistValue({sublistId:m.name, fieldId:m.permLevelField, value:applyingLevel, forceSyncSourcing:true});
if(applyingRestriction){
roleRec.setCurrentSublistValue({sublistId:m.name, fieldId:m.restricted, value:applyingRestriction, forceSyncSourcing:true});
}
roleRec.commitLine({sublistId:m.name});
}, idx *20);
});
lines.forEach((line, idx)=>{
console.log('adding ', m.name, JSON.stringify(line));
setTimeout(()=>{
roleRec.selectNewLine({sublistId:m.name});
roleRec.setCurrentSublistValue({sublistId:m.name, fieldId:m.permRef, value:line.perm, forceSyncSourcing:true});
roleRec.setCurrentSublistValue({sublistId:m.name, fieldId:m.permLevelField, value:line.level, forceSyncSourcing:true});
if(m.restricted){
roleRec.setCurrentSublistValue({sublistId:m.name, fieldId:m.restricted, value:line.restricted, forceSyncSourcing:true });
}
roleRec.commitLine({sublistId:m.name, ignoreRecalc:true});
}, idx*100);
});
});
return id;
}).catch(e=>{
console.error(e.message);
return null;
});
}
doPerms();
}
//load role
//for each machine
// transfer perms
// check current level - use highest
function selectValue(node, path) {
const targets = xml.XPath.select({
node: node,
xpath: path
});
if (!targets || !targets.length) return null;
return targets[0].firstChild.nodeValue;
}
// function selectAttribute(node, path, attr) {
// const targets = xml.XPath.select({
// node: node,
// xpath: path
// });
// if (!targets || !targets.length) return null;
// return targets[0].getAttribute(attr);
// }
function iter(rec, listName, cb){
var lim = rec.getLineCount({sublistId:listName});
var i = 0;
var getV = function (fld){
return rec.getSublistValue({sublistId:listName, fieldId:fld, line:i});
};
for(; i< lim; i++){
cb(i, getV);
}
}
async function fetchWithRetry(url, opts, tries = 3) {
const errs = [];
const waiter = async (pause) => {
return new Promise(resolve => {
setTimeout(() => {
resolve(null);
}, pause);
});
};
for (let i = 0; i < tries; i++) {
// log for illustration
if(i != 0) console.error(`trying GET '${url}' [${i + 1} of ${tries}]`);
try {
const resp = await fetch(url, opts);
return resp;
} catch (err) {
errs.push(err);
await waiter(800 * i + 1);
}
}
throw errs;
}
});

LocalStorage set and get using select2 multiple

I'm having a trouble on how can I save and get multiple list in localStorage and retain data to my select. I tried to set and get the item but when the page reload the data does not retain in my select. I also tried printing the list through console.log as you can see in the image the localStorage contain list value . The only problem I encountered , it does not retain the multiple data in my select when reloads. It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance!
References:link1
let data = [{"id":1,"name":"USA","parentid":0},
{"id":2,"name":"Japan","parentid":0},
{"id":3,"name":"Europe","parentid":0},
{"id":4,"name":"California","parentid":1},
{"id":5,"name":"Oklahoma","parentid":1},
{"id":6,"name":"Arizona","parentid":1},
{"id":7,"name":"Kantô","parentid":2},
{"id":8,"name":"Kansai","parentid":2},
{"id":9,"name":"Chügoku","parentid":2},
{"id":10,"name":"France","parentid":3},
{"id":11,"name":"Deutschland","parentid":3},
{"id":12,"name":"Espana","parentid":3},
{"id":13,"name":"Sacramento","parentid":4},
{"id":14,"name":"Los Angeles","parentid":4},
{"id":15,"name":"San Diego","parentid":4},
{"id":16,"name":"Tulsa","parentid":5},
{"id":17,"name":"Oklahoma City","parentid":5},
{"id":18,"name":"Lawton","parentid":5},
{"id":19,"name":"Phoenix","parentid":6},
{"id":20,"name":"Flagstaff","parentid":6},
{"id":21,"name":"Tucson","parentid":6},
{"id":21,"name":"Tokyo","parentid":7},
{"id":22,"name":"Chiba","parentid":7},
{"id":23,"name":"Tochigi","parentid":7},
{"id":24,"name":"Kyoto","parentid":8},
{"id":25,"name":"Osaka","parentid":8},
{"id":26,"name":"Nara","parentid":8},
{"id":27,"name":"Tottori","parentid":9},
{"id":28,"name":"Hirochima","parentid":9},
{"id":29,"name":"Okayama","parentid":9},
{"id":30,"name":"Quimper","parentid":10},
{"id":31,"name":"Toulouse","parentid":10},
{"id":32,"name":"Nancy","parentid":10},
{"id":33,"name":"Dusseldorf","parentid":11},
{"id":34,"name":"Leipzig","parentid":11},
{"id":35,"name":"Munchen","parentid":11},
{"id":36,"name":"Barcelona","parentid":12},
{"id":37,"name":"Sevilla","parentid":12},
{"id":38,"name":"Guernica","parentid":12}]
function populateList(list, props) {
if(props[0].value != -1){
let l = document.getElementById(list);
l.innerHTML = "";
let topItem = document.createElement("option");
topItem.value = -1;
topItem.text = "--Select--";
l.appendChild(topItem);
for(let i=0; i< props.length; i++){
let newOptGroup = document.createElement("optgroup");
let item = props[i];
let items = data.filter(it => it.parentid == item.value);
items.forEach(function(it){
let newItem = document.createElement("option");
newItem.value = it.id;
newItem.text = it.name;
if(props.length>0 && props[0].value !=0){
newOptGroup.label= item.key
newOptGroup.appendChild(newItem)
}
else l.appendChild(newItem);
})
if(props.length>0 && props[0].value !=0 && props[0].value !=-1){
l.appendChild(newOptGroup)
}
}
}
}
function updateList(selList, thisList) {
let values = [];
for(let i=0;i<thisList.selectedOptions.length; i++) values.push({
key: thisList.selectedOptions[i].label,
value: parseInt(thisList.selectedOptions[i].value)
})
if (values.length>0 && values[0] != 0) {
populateList(selList, values);
} else {
let s = document.getElementById(selList);
s.value = "";
triggerEvent(s, "onchange");
let sCopy = s.cloneNode(false);
let p = s.parentNode;
p.replaceChild(sCopy, s);
}
}
function triggerEvent(e, trigger)
{
if ((e[trigger] || false) && typeof e[trigger] == 'function')
{
e[trigger](e);
}
}
function loadList1() {
populateList("province[]", [{key: '', value: 0}]);
}
window.onload = loadList1;
function reload_and_saveLocalStorage(){
savedlocalStorage();
gettingLocalStorage();
//reload page
window.location.reload(true);
}
function savedlocalStorage(){
//province setting item to LocalStorage
const province_options = document.getElementById('province[]').options;
var prov_selected = [];
Array.from(province_options).map((option) => {
if (option.selected) {
prov_selected.push(option.value);
}
});
localStorage.setItem("province_localstorage", JSON.stringify(prov_selected));
//municipality setting item to LocalStorage
const muni_options = document.getElementById('municipality[]').options;
var muni_selected = [];
Array.from(muni_options).map((option) => {
if (option.selected) {
muni_selected.push(option.value);
}
});
localStorage.setItem("muni_localstorage", JSON.stringify(muni_selected));
//barangay setting item to LocalStorage
const barangay_options = document.getElementById('barangay[]').options;
var barangay_selected = [];
Array.from(barangay_options).map((option) => {
if (option.selected) {
barangay_selected.push(option.value);
}
});
localStorage.setItem("barangay_localstorage", JSON.stringify(barangay_selected));
}
function gettingLocalStorage(){
//Province getting item to Localstorage and display to select
var province_selected = JSON.parse(localStorage.getItem("province_localstorage"));
const province_options = document.getElementById('province[]').options;
Array.from(province_options).map((option) => {
if(province_selected.indexOf(option.value) !== -1) {
option.setAttribute("selected", "selected");
}
});
$(".prov").change();
//Municipality getting item to Localstorage and display to select
var muni_selected = JSON.parse(localStorage.getItem("muni_localstorage"));
const muni_options = document.getElementById('municipality[]').options;
Array.from(muni_options).map((option) => {
if(muni_selected.indexOf(option.value) !== -1) {
option.setAttribute("selected", "selected");
}
});
$(".muni").change();
//barangay getting item to Localstorage and display to select
var barangay_selected = JSON.parse(localStorage.getItem("barangay_localstorage"));
const barangay_options = document.getElementById('barangay[]').options;
Array.from(barangay_options).map((option) => {
if(barangay_selected.indexOf(option.value) !== -1) {
option.setAttribute("selected", "selected");
}
});
$(".brgy").change();
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
Region: <select class = "prov" id="province[]" onchange="updateList('municipality[]', this);" multiple="multiple"></select>
Sub-region:<select class="muni" id="municipality[]" onchange="updateList('barangay[]', this);" multiple="multiple"></select>
Location:<select class="brgy" id="barangay[]" multiple="multiple"></select>
<button onclick="reload_and_saveLocalStorage()">SAVE AND RELOAD </button>
Can't execute the snippet beacuse is not secure envolving localStorage, but my advice is to try
$(".brgy").val(option.value);
Instead of setting the "selected" attribute on the option.
That should work.

Could someone please explain how to properly write this Javascript function?

I'm looking for someone to show me where I went wrong. The instructions are as follows:
Write the following function (use the songs array to determine what to return).
getSongsNamesByArtist - this function expects a string as an argument
and returns an array containing the names of only those songs in
the songs array whose artist properties are equal to the string
that is passed to it.
So I did this:
let songs = [];
function createSong(name, artist) {
let song = {
name: name,
artist: artist
}
songs.push(song);
return song;
}
var heroes = new createSong("Heroes", "Bowie");
var jubileeStreet = new createSong("Jubilee Street", "Nick Cave");
var buena = new createSong("Buena", "Morphine");
var changes = new createSong("Changes", "Bowie");
var belaLugosi = new createSong("Bela Lugosi is Dead", "Bauhaus");
// I could get only this far:
function getSongsNamesByArtist(artist) {
let names = [];
for (let i = 0; i < songs.length; i++) {
let song = songs[i];
if (song.artist === artist) {
names.push(song.name);
return names;
}
}
}
console.log(getSongsNamesByArtist("Bowie")) // returns: [ 'Heroes' ], but not both of them.
Could you please give me a hint where I went wrong?
Thanks for your time!
The problem is that you are doing an early return in the if statement. So as soon as you are finding a match you return the result.
function getSongsNamesByArtist(artist) {
let names = [];
for (let i = 0; i < songs.length; i++) {
let song = songs[i];
if (song.artist === artist) {
names.push(song.name);
return names; // <- here is your problem
}
}
}
Instead, you want to return after the loop.
function getSongsNamesByArtist(artist) {
let names = [];
for (let i = 0; i < songs.length; i++) {
let song = songs[i];
if (song.artist === artist) {
names.push(song.name);
}
}
return names; // <- here is where you should return
}
You can also consider refactoring this function with the filter and map function in JS
function getSongsNamesByArtist(artist) {
return songs.filter((song) => {
// Filter out the artist you are looking for
return song.artist === artist;
}).map((song) => {
// Reformat your output to only contain the name of the song
return song.name;
});
}
You were returning as soon as first match is found. You have to do it outside for loop . Update your method as below
let songs = [];
function createSong(name, artist) {
let song = {
name: name,
artist: artist
}
songs.push(song);
return song;
}
var heroes = new createSong("Heroes", "Bowie");
var jubileeStreet = new createSong("Jubilee Street", "Nick Cave");
var buena = new createSong("Buena", "Morphine");
var changes = new createSong("Changes", "Bowie");
var belaLugosi = new createSong("Bela Lugosi is Dead", "Bauhaus");
// I could get only this far:
function getSongsNamesByArtist(artist) {
let names = [];
for (let i = 0; i < songs.length; i++) {
let song = songs[i];
if (song.artist === artist) {
names.push(song.name);
}
}
return names;
}
console.log(getSongsNamesByArtist("Bowie"))

amazon-chime-sdk-js display self video

I created a video application using chime js SDK with the help of the documentation https://aws.github.io/amazon-chime-sdk-js/index.html
const indexMap = {};
const acquireVideoElement = tileId => {
for (let i = 0; i < 16; i += 1) {
if (indexMap[i] === tileId) {
return videoElements[i];
}
}
for (let i = 0; i < 16; i += 1) {
if (!indexMap.hasOwnProperty(i)) {
indexMap[i] = tileId;
return videoElements[i];
}
}
throw new Error('no video element is available');
};
const releaseVideoElement = tileId => {
for (let i = 0; i < 16; i += 1) {
if (indexMap[i] === tileId) {
delete indexMap[i];
return;
}
}
};
const observer = {
videoTileDidUpdate: tileState => {
if (!tileState.boundAttendeeId || tileState.localTile || tileState.isContent) {
return;
}
meetingSession.audioVideo.bindVideoElement(tileState.tileId, acquireVideoElement(tileState.tileId));
},
videoTileWasRemoved: tileId => {
releaseVideoElement(tileId);
}
};
meetingSession.audioVideo.addObserver(observer);
const audioMix = document.getElementById('meeting-audio');
meetingSession.audioVideo.bindAudioElement(audioMix);
meetingSession.audioVideo.start();
meetingSession.audioVideo.startLocalVideoTile();
This is working good and I can see all the attendees who is joined in the meeting. But I need to show my video also in a tag. Is it possible?
In your videoTileDidUpdate, for your video tile to show, where are you binding the local tile, I see that if tileState.localTile is true you are returning and the bindVideoElement is not getting called hence your localTile is not showing up. Can you please remove the localTile check and see if that works as the initial step.
videoTileDidUpdate: tileState => {
// Ignore a tile without attendee ID, a local tile (your video), and a content share.
const { allUsers } = this.props;
if (!tileState.boundAttendeeId || tileState.isContent) {
return;
}
if( tileState.localTile ) {
if( Obj[tileState.boundExternalUserId]['tileId'] === tileState.tileId) {
return;
}
}
this.meetingSession.current.audioVideo.bindVideoElement( tileState.tileId,document.getElementById(tileState.boundExternalUserId) );
}

Node js: Object pushes into an array before few object properties hasn't been returned from promise

I am trying to hit an api and setting data to an object properties. I am setting few properties inside javascript promise and then pushing object in array outside the promise. So now object pushed before values returned from promise. How to solve this?
My code is here.
const getUserExchangeAccountDetails = function(props, params, callback) {
const client = new bittrex(constants.bittrexApiKey, constants.bittrexSecretKey);
let responseArray = [];
let tempArr = [];
let otherArr = [];
let coinNumber = 0;
return new Promise(function(resolve, reject) {
client.getbalances(function (err, response, taskcallback) {
if (err) {
reject(err);
} else {
let coinsList = response.result;
console.log("Results-----", response.result);
for(let i = 0; i < response.result.length; i++ ){
let coin = {
currency : "",
balance : 0,
usdPrice : 0,
coinsInUsd : [],
totalCoins : 0,
};
if(response.result[i].Currency != null ||
response.result[i].Currency != ""){
coin.currency = response.result[i].Currency;
}
if(response.result[i].Balance > 0 ){
coin.balance = response.result[i].Balance;
}
if(coin.currency != "" && coin.balance > 0){
coinNumber = coinNumber + 1;
coin.totalCoins = coinNumber;
if (coin.currency != 'BTCP') {
currenciesService.getCurrencyLatestInfo(coin.currency).then((data) => {
coin.usdPrice = data;
let usdData = conversionIntoDollar.coinsConversionInUsd(coin.balance, coin.usdPrice);
coin.coinsInUsd.push(usdData);
});
}
responseArray.push(coin);
console.log(responseArray);
}
}
resolve(responseArray);
} //else
});
})
}
Here is output of my code, values returning form promises are empty, rest of the properties are working fine.
Output Data screenshot

Categories

Resources