javascript to filter unwanted data - javascript

I am new to angular js. I have a link http://www.bursamalaysia.com/searchbox_data.json that I want to get a list of name and id.
I able to get the list from a link in json but I need to filter unwanted items in the list. If the id is more than 4 digits, then remove full_name,name, short_name and id. example: if id:123456 , it need to be filter out, together with name,short name.
app.js
abc: {
name: "Momo",
value: "kls",
long: "KLSE",
searchRef: KLSE_SEARCH_REF,
searchRefURL: "http://www.bursamalaysia.com/searchbox_data.json",
},
details.js
$ionicLoading.show();
if ($scope.currentMarket == "abc"){
$webServicesFactory.getNotParsed($marketProvider[$scope.currentMarket].searchRefURL).then(function success(response){
response = JSON.parse(response);
for (var i = 0; i < response[0].length; i++){
$scope.searchRef.push({
name: response[0][i].name || response[0][i].full_name,
symbol: response[0][i].short_name,
code: response[0][i].id,
market: $marketProvider[$scope.currentMarket].long
});
}
console.info($scope.searchRef);
$ionicLoading.hide();
});
}
html
<div class="list">
<div class="item" ng-repeat="item in searchItems" ng-click="openDetail(item)">
<p>{{item.symbol}} - {{item.name}}</p>
<p>{{currentMarket | uppercase}}</p>
</div>
</div>

You could go with Array.prototype.filter and Array.prototype.map, which is quite elegant.
$ionicLoading.show();
if($scope.currentMarket == "abc") {
$webServicesFactory.getNotParsed($marketProvider[$scope.currentMarket].searchRefURL).then(
function success(response) {
$scope.searchRef = JSON.parse(response)[0].filter(function(itm) {
// whatever you want to filter should pass this condition
return itm.id.toString().length <= 3;
}).map(function(itm) {
// for each item, transform to this
return {
name: itm.name || itm.full_name,
symbol: itm.short_name,
code: itm.id,
market: $marketProvider[$scope.currentMarket].long
};
});
$ionicLoading.hide();
}
);
}
Make sure to handle any errors and to make your code defensive.

if you need filter more than 4 digit id values , then you can restrict with simple condition if(response[0][i].id <= 999)
example below:
for(var i=0; i<response[0].length; i+=1){
if(response[0][i].id.toString().length <= 3 ) {
$scope.searchRef.push(
{
name: response[0][i].name || response[0][i].full_name,
symbol: response[0][i].short_name,
code: response[0][i].id,
market: $marketProvider[$scope.currentMarket].long
}
);
}
}

Related

How to filter undefined values from Array JavaScript?

The code below is working fine it's filtering duplicate values from Array but it's not filtering undefined Values console.log([67, undefined]). i want to filter undefined values and duplicate values from array and output in options values as selected. I would be grateful for any help.
i have two datatable with drag and drop functionality. each row of datatable contain the IDs. when i drag the row of table 1 into table 2. the data stored into the Array. i have the addArray function for push the IDs into an Array there also filtering the duplicate IDs and make it uniqueArray. now i want to create the Select option Element which containing the iDs as a value. I want if i drag out a value from Array then the select options update automatically and delete the option from it...?
js
$(document).ready(function () {
new Sortable(drag, {
group: 'sortables',
multiDrag: true, // Enable multi-drag
selectedClass: 'selected', // The class applied to the selected items
fallbackTolerance: 3, // So that we can select items on mobile
animation: 150,
onUpdate: function (e, tr) {
addArray();
checkFields();
},
});
new Sortable(drop, {
group: "sortables",
multiDrag: true, // Enable multi-drag
selectedClass: 'selected', // The class applied to the selected items
fallbackTolerance: 3, // So that we can select items on mobile
animation: 150,
onChange: function (event, tr) {
Sorting();
addArray();
checkFields();
},
});
function addArray() {
let uniqueArray = [],
html = [];
$('#drop').children().each(function () {
const pk = $(this).data('pk');
if (pk && !uniqueArray.includes(pk)) {
uniqueArray.push(pk);
html.push(`<option value="${pk}">${pk}</option>`);
}
});
$('#id_articles').html(html.join(""))
}
function Sorting() {
sort = [];
$('#drop').children().each(function () {
sort.push({ 'pk': $(this).data('pk'), 'order': $(this).index() })
});
let crf_token = $('[name="csrfmiddlewaretoken"]').attr('value') // csrf token
$.ajax({
url: "/rundown/sorts/",
type: "post",
headers: { "X-CSRFToken": crf_token },
datatype: 'json',
data: {
'sort': JSON.stringify(sort),
},
success: function () {
console.log('success')
}
});
};
function checkFields() {
if ($('#drop tr').length >= 1) {
$('#drop').find('#blank_row').remove();
} else {
$('#drop').append($("<tr>").attr("id", "blank_row")
.append($('<td>').attr("colspan", '4')
.text('Drop here...')));
}
};
});
You do not have a filter. Why not just test
function stop_duplicate_in_array(array, value) {
if (!value && value !== 0) return array; // value is falsy but not 0
if (!array.includes(value)) array.push(value);
return array;
}
if 0 is not a possible value, remove && value !== 0
function stop_duplicate_in_array(array, value) {
if (value && !array.includes(value)) array.push(value);
return array;
}
You can simplify
function addArray() {
let uniqueArray = [],
html = [];
$('#drop').children().each(function() {
const pk = $(this).data('pk');
if (pk && !uniqueArray.includes(pk)) {
uniqueArray.push(pk);
html.push(`<option value="${pk}">${pk}</option>`);
}
});
$('#id_articles').html(html.join(""))
}
addArray()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="drop">
<article data-pk="A">A</article>
<article>Undefined</article>
<article data-pk="B">B</article>
<article data-pk="">Empty</article>
<article data-pk="C">C</article>
</div>
<select id="id_articles"></select>
Some remarks:
Currently you are adding a value, then removing it again in the stop-function, and adding it yet again. True, the values will be unique, but this is not very efficient. Use a Set for efficiently making a collection unique.
Use jQuery more to the full when creating option elements
To answer your question: just check for undefined before including it. But if you use the Set-way of working (see point 1), you can just delete undefined from that Set
Here is how it could look:
function addArray() {
let articles = new Set(
$('#drop').children().map((i, elem) => $(elem).data('pk')).get()
);
articles.delete(undefined);
$('#id_articles').empty().append(
Array.from(articles, value => $("<option>", { value }).text(value))
);
}
addArray();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="drop">
<div data-pk="red"></div>
<div data-pk="blue"></div>
<div data-pk="red"></div>
<div></div>
</div>
<select id="id_articles"></select>
Simply compare element with undefined
const array = [1,2,undefined,3,4,undefined,5];
const result = array.filter((el) => el !== undefined);
console.log(result)

How to loop through HTML elements and populate a Json-object?

I'm looping through all the html tags in an html-file, checking if those tags match conditions, and trying to compose a JSON-object of a following schema:
[
{ title: 'abc', date: '10.10.10', body: ' P tags here', href: '' },
{ title: 'abc', date: '10.10.10', body: ' P tags here', href: '' },
{ title: 'abc', date: '10.10.10', body: ' P tags here', href: '' }
]
But I'd like to create the new entry only for elements, classed "header", all the other elements have to be added to earlier created entry. How do I achieve that?
Current code:
$('*').each((index, element) => {
if ( $(element).hasClass( "header" ) ) {
jsonObject.push({
title: $(element).text()
});
};
if( $(element).hasClass( "date" )) {
jsonObject.push({
date: $(element).text()
});
}
//links.push($(element))
});
console.log(jsonObject)
Result is:
{
title: 'TestA'
},
{ date: '10.10.10' },
{
title: 'TestB'
},
{ date: '10.10.11' }
I'd like it to be at this stage something like:
{
title: 'TestA'
,
date: '10.10.10' },
{
title: 'TestB'
,
date: '10.10.11' }
UPD:
Here's the example of HTML file:
<h1 class="header">H1_Header</h1>
<h2 class="date">Date</h2>
<p>A.</p>
<p>B.</p>
<p>С.</p>
<p>D.</p>
<a class="source">http://</a>
<h1 class="header">H1_Header2</h1>
<h2 class="date">Date2</h2>
<p>A2.</p>
<p>B2.</p>
<p>С2.</p>
<p>D2.</p>
<a class="source">http://2</a>
Thank you for your time!
Based on your example Html, it appears everything you are trying to collect is in a linear order, so you get a title, date, body and link then a new header with the associated items you want to collect, since this appears to not have the complication of having things being ordered in a non-linear fasion, you could do something like the following:
let jsonObject = null;
let newObject = false;
let appendParagraph = false;
let jObjects = [];
$('*').each((index, element) => {
if ($(element).hasClass("header")) {
//If newObject is true, push object into array
if(newObject)
jObjects.push(jsonObject);
//Reset the json object variable to an empty object
jsonObject = {};
//Reset the paragraph append boolean
appendParagraph = false;
//Set the header property
jsonObject.header = $(element).text();
//Set the boolean so on the next encounter of header tag the jsobObject is pushed into the array
newObject = true;
};
if( $(element).hasClass( "date" )) {
jsonObject.date = $(element).text();
}
if( $(element).prop("tagName") === "P") {
//If you are storing paragraph as one string value
//Otherwise switch the body var to an array and push instead of append
if(!appendParagraph){ //Use boolean to know if this is the first p element of object
jsonObject.body = $(element).text();
appendParagraph = true; //Set boolean to true to append on next p and subsequent p elements
} else {
jsonObject.body += (", " + $(element).text()); //append to the body
}
}
//Add the href property
if( $(element).hasClass("source")) {
//edit to do what you wanted here, based on your comment:
jsonObject.link = $(element).next().html();
//jsonObject.href= $(element).attr('href');
}
});
//Push final object into array
jObjects.push(jsonObject);
console.log(jObjects);
Here is a jsfiddle for this: https://jsfiddle.net/Lyojx85e/
I can't get the text of the anchor tags on the fiddle (I believe because nested anchor tags are not valid and will be parsed as seperate anchor tags by the browser), but the code provided should work in a real world example. If .text() doesn't work you can switch it to .html() on the link, I was confused on what you are trying to get on this one, so I updated the answer to get the href attribute of the link as it appears that is what you want. The thing is that the anchor with the class doesn't have an href attribute, so I'll leave it to you to fix that part for yourself, but this answer should give you what you need.
$('*').each((index, element) => {
var obj = {};
if ( $(element).hasClass( "header" ) ) {
obj.title = $(element).text();
};
if( $(element).hasClass( "date" )) {
obj.date = $(element).text()
}
jsonObject.push(obj);
});
I don't know about jQuery, but with JavaScript you can do with something like this.
const arr = [];
document.querySelectorAll("li").forEach((elem) => {
const obj = {};
const title = elem.querySelector("h2");
const date = elem.querySelector("date");
if (title) obj["title"] = title.textContent;
if (date) obj["date"] = date.textContent;
arr.push(obj);
});
console.log(arr);
<ul>
<li>
<h2>A</h2>
<date>1</date>
</li>
<li>
<h2>B</h2>
</li>
<li>
<date>3</date>
</li>
</ul>
Always use map for things like this. This should look something like:
let objects = $('.header').get().map(el => {
return {
date: $(el).attr('date'),
title: $(el).attr('title'),
}
})

Vue.js 2 - Array change detection

Here's a simplified version of my code :
<template>
/* ----------------------------------------------------------
* Displays a list of templates, #click, select the template
/* ----------------------------------------------------------
<ul>
<li
v-for="form in forms.forms"
#click="selectTemplate(form)"
:key="form.id"
:class="{selected: templateSelected == form}">
<h4>{{ form.name }}</h4>
<p>{{ form.description }}</p>
</li>
</ul>
/* --------------------------------------------------------
* Displays the "Editable fields" of the selected template
/* --------------------------------------------------------
<div class="form-group" v-for="(editableField, index) in editableFields" :key="editableField.id">
<input
type="text"
class="appfield appfield-block data-to-document"
:id="'item_'+index"
:name="editableField.tag"
v-model="editableField.value">
</div>
</template>
<script>
export default {
data: function () {
return {
editableFields: [],
}
},
methods: {
selectTemplate: function (form) {
/* ------------------
* My problem is here
*/ ------------------
for (let i = 0; i < form.editable_fields.length; i++) {
this.editableFields.push(form.editable_fields[i]);
}
}
}
}
</script>
Basically I want to update the array EditableFields each time the user clicks on a template. My problem is that Vuejs does not update the display because the detection is not triggered. I've read the documentation here which advise to either $set the array or use Array instance methods only such as splice and push.
The code above (with push) works but the array is never emptied and therefore, "editable fields" keep pilling up, which is not a behavior I desire.
In order to empty the array before filling it again with fresh data, I tried several things with no luck :
this.editableFields.splice(0, this.editableFields.length);
for (let i = 0; i < form.editable_fields.length; i++) {
this.editableFields.push(form.editable_fields[i]);
}
==> Does not update the display
for (let i = 0; i < form.editable_fields.length; i++) {
this.$set(this.editableFields, i, form.editable_fields[i]);
}
==> Does not update the display
this.editableFields = form.editable_fields;
==> Does not update the display
Something I haven't tried yet is setting a whole new array with the fresh data but I can't understand how I can put that in place since I want the user to be able to click (and change the template selection) more than once.
I banged my head on that problem for a few hours now, I'd appreciate any help.
Thank you in advance :) !
I've got no problem using splice + push. The reactivity should be triggered normally as described in the link you provided.
See my code sample:
new Vue({
el: '#app',
data: function() {
return {
forms: {
forms: [{
id: 'form1',
editable_fields: [{
id: 'form1_field1',
value: 'form1_field1_value'
},
{
id: 'form1_field2',
value: 'form1_field2_value'
}
]
},
{
id: 'form2',
editable_fields: [{
id: 'form2_field1',
value: 'form2_field1_value'
},
{
id: 'form2_field2',
value: 'form2_field2_value'
}
]
}
]
},
editableFields: []
}
},
methods: {
selectTemplate(form) {
this.editableFields.splice(0, this.editableFields.length);
for (let i = 0; i < form.editable_fields.length; i++) {
this.editableFields.push(form.editable_fields[i]);
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
<ul>
<li v-for="form in forms.forms"
#click="selectTemplate(form)"
:key="form.id">
<h4>{{ form.id }}</h4>
</li>
</ul>
<div class="form-group"
v-for="(editableField, index) in editableFields"
:key="editableField.id">
{{ editableField.id }}:
<input type="text" v-model="editableField.value">
</div>
</div>
Problem solved... Another remote part of the code was in fact, causing the problem.
For future reference, this solution is the correct one :
this.editableFields.splice(0, this.editableFields.length);
for (let i = 0; i < form.editable_fields.length; i++) {
this.editableFields.push(form.editable_fields[i]);
}
Using only Array instance methods is the way to go with Vuejs.

Why can't my post functions access a variable above it?

I'm trying to figure out why the post functions at the end of the following code do not have access to the userID variable (I'm assuming it's a scope issue as logging userId immediately before the functions returns the correct value).
$.get("/set_languages_user", function(res) {
console.log(res)
if ( res.length === 0 ) {
var getUserInfo = $.get('/set_user', function(res){
var langConfirmSource = $('#language-confirmation-template').html();
var langConfirmCompiled = Handlebars.compile(langConfirmSource);
var langConfirmTemplate = langConfirmCompiled(res)
$('body').append(langConfirmTemplate)
$('html').toggleClass('disable_scrolling')
var userId = res.id
var native_language = res.native_language
var learning_language = res.learning_language
$(document).on('submit', '#language_confirmation', function(e){
e.preventDefault()
// prevent user from continuing if they haven't checked that they agree to the term's of use
if ( $('#touCheck').is(':checked')) {
console.log('checked!!!')
// this function finds the ID of the User's defined languages
var getUserInfo = $.get('/languages.json', function(lang){
// Find the ID of the languages the User is supporting in order to submit to languages_users db
for (i = 0; i < lang.length; i++) {
if (lang[i].language === native_language) {
var confirmedUserNativeInt = lang[i].id
}
}
for (i = 0; i < lang.length; i++) {
if (lang[i].language === learning_language) {
var confirmedUserLearningInt = lang[i].id
}
}
console.log(confirmedUserNativeInt)
console.log(confirmedUserLearningInt)
console.log(userId)
// creates a new instance in languages_user for the learningLanguage (level 1)
$.post( "/languages_users", { languages_user:{ language_id: confirmedUserLearningInt, user_id: userId, level: 1 }})
// creates a new instance in languages_user for the nativelanguage (level 5)
$.post( "/languages_users", { languages_user:{ language_id: confirmedUserNativeInt, user_id: userId, level: 5 } })
$('.signon_language_confirmation').remove()
$('html').toggleClass('disable_scrolling')
});
} else {
console.log('not checked!!!')
$('.wrapper_tou_signup').append('<p class="message_form_error">You must agree to Lexody\'s Terms of Use to continue.</p>')
}
})
});
}
})
Here is the handlebars template that is being rendered:
<script id="language-confirmation-template" type="text/x-handlebars-template">
<div class="signon_language_confirmation">
<p class="title_langconf">Welcome to</p>
<img src="">
<div class="wrapper_form_dark language_confirmation_form wrapper_form_sign_on">
<form id="language_confirmation">
<div class="form_section">
<div class="wrapper_input col_16_of_16">
<p>I speak {{native_language}} <svg class="icon_standard"><use xlink:href="#{{native_language}}"/></svg></p>
<p>I am learning {{learning_language}} <svg class="icon_standard"><use xlink:href="#{{learning_language}}"/></svg></p>
<div class="wrapper_tou_signup">
<p><input type="checkbox" name="tou" value="agree" id="touCheck"> I agree to Lexody's terms of use.</p>
</div>
<div class="submit_cancel">
<input type="submit" value="Submit" class="btn_primary submit">
</div>
</div>
</div>
</form>
</div>
</div>
When I submit I'm getting "Uncaught ReferenceError: userId is not defined(…)". How do I make that variable accessible to those functions and why is that variable not accessible but the others ('confirmedUserLearningInt' and 'confirmedUserNativeInt') are?
Thanks in advance.
you have not declared the var's somewhere where the post method can reach, as you can see in your code the vars are inside a if statement which is inside a for loop, you should declare the var before the for loop like this:
$.get("/set_languages_user", function(res) {
console.log(res)
if ( res.length === 0 ) {
var getUserInfo = $.get('/set_user', function(res){
var langConfirmSource = $('#language-confirmation-template').html();
var langConfirmCompiled = Handlebars.compile(langConfirmSource);
var langConfirmTemplate = langConfirmCompiled(res)
$('body').append(langConfirmTemplate)
$('html').toggleClass('disable_scrolling')
var userId = res.id
var native_language = res.native_language
var learning_language = res.learning_language
$(document).on('submit', '#language_confirmation', function(e){
e.preventDefault()
// prevent user from continuing if they haven't checked that they agree to the term's of use
if ( $('#touCheck').is(':checked')) {
console.log('checked!!!')
// this function finds the ID of the User's defined languages
var getUserInfo = $.get('/languages.json', function(lang){
// Find the ID of the languages the User is supporting in order to submit to languages_users db
var confirmedUserNativeInt; //<<<<<<<<<<<<<<
for (i = 0; i < lang.length; i++) {
if (lang[i].language === native_language) {
confirmedUserNativeInt = lang[i].id
}
}
var confirmedUserLearningInt;//<<<<<<<<<<<<<<<<
for (i = 0; i < lang.length; i++) {
if (lang[i].language === learning_language) {
confirmedUserLearningInt = lang[i].id
}
}
console.log(confirmedUserNativeInt)
console.log(confirmedUserLearningInt)
console.log(userId)
// creates a new instance in languages_user for the learningLanguage (level 1)
$.post( "/languages_users", { languages_user:{ language_id: confirmedUserLearningInt, user_id: userId, level: 1 }})
// creates a new instance in languages_user for the nativelanguage (level 5)
$.post( "/languages_users", { languages_user:{ language_id: confirmedUserNativeInt, user_id: userId, level: 5 } })
$('.signon_language_confirmation').remove()
$('html').toggleClass('disable_scrolling')
});
} else {
console.log('not checked!!!')
$('.wrapper_tou_signup').append('<p class="message_form_error">You must agree to Lexody\'s Terms of Use to continue.</p>')
}
})
});
}
})

Shorten function in Javascript / Jquery

LF way to short my js/jquery function:
$.ajax({ // Start ajax post
..........
success: function (data) { // on Success statment start
..........
//1. Part
$('var#address').text(data.address);
$('var#telephone').text(data.telephone);
$('var#mobile').text(data.mobile);
$('var#fax').text(data.fax);
$('var#email').text(data.email);
$('var#webpage').text(data.webpage);
//2. Part
if (!data.address){ $('p#address').hide(); } else { $('p#address').show(); };
if (!data.telephone){ $('p#telephone').hide(); } else { $('p#telephone').show(); };
if (!data.mobile){ $('p#mobile').hide(); } else { $('p#mobile').show(); };
if (!data.fax){ $('p#fax').hide(); } else { $('p#fax').show(); };
if (!data.email){ $('p#email').hide(); } else { $('p#email').show(); };
if (!data.webpage){ $('p#webpage').hide(); } else { $('p#webpage').show(); };
}, End Ajax post success statement
Here is my html:
<p id="address">Address:<var id="address">Test Street 999 2324233</var></p>
<p id="telephone">Telephone:<var id="telephone">+1 0000009</var></p>
<p id="mobile">Mobile:<var id="mobile">+1 0000009</var></p>
<p id="email">E-mail:<var id="email">info#example</var></p>
<p id="webpage">Web Page:<var id="webpage">www.example.com</var>/p>
How can we reduce the number of selector*(1. part)* and else if the amount (2. part)?
Assuming your object's property names exactly match the spelling of your element ids you can do this:
for (var k in data) {
$('var#' + k).text(data[k]);
$('p#' + k).toggle(!!data[k]);
}
...because .toggle() accepts a boolean to say whether to show or hide. Any properties that don't have a matching element id would have no effect.
Note: your html is invalid if you have multiple elements with the same ids, but it will still work because your selectors specify the tag and id. Still, it might be tidier to just remove the ids from the var elements:
<p id="address">Address:<var>Test Street 999 2324233</var></p>
<!-- etc. -->
With this JS:
$('#' + k).toggle(!!data[k]).find('var').text(data[k]);
And then adding some code to hide any elements that aren't in the returned data object:
$('var').parent('p').hide();
...and putting it all together:
$.ajax({
// other ajax params here
success : function(data) {
$('var').parent('p').hide();
for (var k in data) {
$('#' + k).toggle(!!data[k]).find('var').text(data[k]);
}
}
});
Demo: http://jsfiddle.net/z98cw/1/
["address", "telephone", "mobile", "fax", "email", "webpage"].map(
function(key) {
if (data.hasOwnProperty(key) && !!data[key]) {
$('p#' + key).show();
} else {
$('p#' + key).hide();
}
});
But you should not.
As long as the properties of the object match the id attributes of the p tags you can iterate through the object using the property name as a selector. Also since id attributes are unique, refrain from prefixing the selector with var it is unnecessary.
var data = {
address: "address",
telephone: "telephone",
mobile: "mobile",
fax: "fax",
email: "email",
webpage: "webpage"
};
for(x in data){
var elem = $("#" + x);
if(elem.length == 1){
elem.text(data[x]);
}
}
JS Fiddle: http://jsfiddle.net/3uhx6/
This is what templating systems are created for.
If you insist on using jQuery there is a jQuery plugin: https://github.com/codepb/jquery-template
More:
What Javascript Template Engines you recommend?
I would use javascript templates for this (I've shortened the example a quite a bit, but you should get the gist).
First the template, I love Underscore.js for this so I gonna go ahead and use that.
<% if data.address %>
<p id="address">Address: {%= Test Street 999 2324233 %}</p>
to compile this inside your success function
success: function(data) {
//assuming data is a json that looks like this {'address':'my street'}
var template = _.template(path_to_your_template, data);
$('var#addresscontainer').html(template);
}
Thanks for birukaze and nnnnnn:
With your advice came function;) :
for (var key in data) {
if (data.hasOwnProperty(key) && !!data[key]) {
$('p#' + key).show().find('var').text(data[key]);
} else {
$('p#' + key).hide();
}
};
Now i can avoid for selector with var.

Categories