There are two files. The first:
<div class="someclass">text1</div>
<div class="someclass">text2</div>
<script>
var foo = document.getElementsByClassName("someclass");
var arr = Array.prototype.map.call(foo, function(elem) {
return elem.innerHTML;
});
localStorage.foobar = JSON.stringify(arr);
alert(localStorage.foobar);
</script>
That gives: ["text1","text2"]
The second (files are identical except inner text in first two lines):
<div class="someclass">text3</div>
<div class="someclass">text4</div>
<script>
var foo = document.getElementsByClassName("someclass");
var arr = Array.prototype.map.call(foo, function(elem) {
return elem.innerHTML;
});
localStorage.foobar = JSON.stringify(arr);
alert(localStorage.foobar);
</script>
That gives: ["text3","text4"]
I would like the second file to give ["text1","text2","text3","text4"], or maybe ["text3","text4","text1","text2"].
How can I do that?
You need to retrieve the previously-stored data (if any), and append to that array. Something like:
var foostr = localStorage.foobar || "[]";
arr = JSON.parse(foostr);
var foo = document.getElementsByClassName("someclass");
Array.prototype.forEach.call(foo, function(elem) {
arr.push(elem.innerHTML);
});
localStorage.foobar = JSON.stringify(arr);
alert(localStorage.foobar);
So you need to see if there is anything and concatenate it to the array.
if (localStorage.foobar) {
var prev = JSON.parse(localStorage.foobar);
arr = arr.concat(prev);
}
localStorage.foobar = JSON.stringify(arr);
You can concat the both arrays after retrieving localStorage's contents first, using JSON.parse():
var foo = document.getElementsByClassName("someclass");
var arr = Array.prototype.map.call(foo, function(elem) {
return elem.innerHTML;
});
localStorage.foobar = JSON.stringify(JSON.parse(localStorage.foobar).concat(arr));
console.log(localStorage.foobar);
Related
I've got the following parameters
/Search?category=1&attributes=169&attributes=172&attributes=174&search=all
I'm trying to get just the attributes querystring values as an array in javascript, for example.
attributes = ['169','172','174']
Bearing in mind there may be other parameters that are irrelevant such as search or category.
Might not the proper answer but just tried
var str = "/Search?category=1&attributes=169&attributes=172&attributes=174&search=all";
var str1 = str.split("&");
var attributesArray = [];
for(var i=0; i<str1.length; i++) {
if (str1[i].includes("attributes")) {
attributesArray.push(str1[i].replace("attributes=", ""));
}
}
Fiddle https://jsfiddle.net/5Lkk0gnz/
You can do it like this:
(function() {
function getJsonFromUrl(url) {
var query = url.substr(1);
var arr = [];
query.split("&").forEach(function(part) {
var item = part.split("=");
arr.push(decodeURIComponent(item[1]));
});
return arr;
}
var url = "https://example.com?category=1&attributes=169&attributes=172&attributes=174&search=all";
var params = getJsonFromUrl(url);
console.log(params);
})();
Hope this helps!
This should do what you want, assuming you already have your url:
var url = "/Search?ategory=1&attributes=169&attributes=172&attributes=174&search=all";
var attrs = url
.match(/attributes=\d*/g)
.map(function(attr){
return Number(attr.replace("attributes=", ""));
});
console.log(attrs); //=> [169, 172, 174]
I have seen a brunch of solution about how to show/hide the div which do not contains(or contains) specific keywords but none of them do help.
So far I have done some codes like this:
<div class="media">Title : orange</div>
<div class="media">this is something about orangessss yolo</div>
<div class="media">Title : apple</div>
<div class="media">this is something about apple yolo</div>
<button id="filter">test</button>
And I have a method to fliter the elements:
var KeywordArr = ["orange","orangessss"];
$('#filter').click(function () {
var key = $(".media");
var word= key.find(".media").html();
if(!word && word.toLowerCase().match([KeywordArr])) {
$(".media").css("display", "none");
}
});
These codes suppose to add "display:none" to every "media" class which does not contains any keywords included in the array. But it's not working as my exception.
So how can I hide all the elements when the "< div"> do not have the value contain in keywordArr?
Solution:
$('#filter').click(function () {
var elems = $(".media");
var KeywordArr = ["orange", "orangessss"];
var res = $();
for (var i = 0; i < KeywordArr.length; i++) {
res = res.add(elems.filter(":contains('" + KeywordArr[i] + "')"));
}
elems.not(res).hide();
});
Try to use :contains() selector at this context,
var elems = $(".media");
var KeywordArr = ["orange", "orangessss"];
var res = $();
for (var i = 0; i < KeywordArr.length; i++) {
res = res.add(elems.filter(":contains('" + KeywordArr[i] + "')"));
}
elems.not(res).hide();
Also note that contains selector is case sensitive.
DEMO
To keep your code more declarative you can use array foreach. also make sure to keep you variable names all lowercase.
var elems = $(".media");
var keywordArr = ["orange", "orangessss"];
var res = $();
keywordArr.forEach(function(keyword){
res = res.add(elems.filter(":contains('" + keyword + "')"));
});
elems.not(res).hide();
Also if you can write the Same code with ES6 Template literals, here is a link to Demo
const elems = $(".media");
const keywordArr = ["orange", "orangessss"];
let res = $();
keywordArr.forEach(
(keyword) => res = res.add(elems.filter(`:contains(${keyword})`))
);
elems.not(res).hide();
I've got json data.
[
["Fruit","Lychee Magic","Dusk"],
["Veggies","Long Beans","Rampage"],
["Fruit","Mango Aroma Sweet","Dawn"]
]
I've got buttons. The first part of the button text is similar to a json data.
<button type="button" class="mood">Mango</button>
<button type="button" class="mood">Lychee</button>
How can I match the button text to the json data and get the full line in to an array?
var butTxArr = [];
$("#intoArr").click(function(){
$('.mood').each(function(){
var obj = //how to match?
butTxArr.push(obj);
})
});
excepted output:
butTxArr = ["Fruit","Lychee Magic","Dusk", "Fruit","Mango Aroma Sweet","Dawn"];
Something like this?
$("#intoArr").click(function () {
var butTxArr = [];
$('.mood').each(function () {
// trim button text
var text = $(this).text().replace(/^\s*/g, '').replace(/\s*$/g, '');
data.forEach(function (row) {
// see if the row contains the text
if (row.toString().indexOf(text) !== -1)
// append to array
butTxArr = butTxArr.concat(row);
})
})
// we're done!
console.log(butTxArr)
});
$(document).ready(function() {
var data = [
["Fruit", "Lychee Magic", "Dusk"],
["Veggies", "Long Beans", "Rampage"],
["Fruit", "Mango Aroma Sweet", "Dawn"]
];
$("#intoArr").click(function() {
var butTxArr = [];
$('.mood').each(function() {
// trim button text
var text = $(this).text().replace(/^\s*/g, '').replace(/\s*$/g, '');
data.forEach(function(row) {
// see if the row contains the text
if (row.toString().indexOf(text) !== -1)
// append to array
butTxArr = butTxArr.concat(row);
})
})
// we're done!
alert(butTxArr)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="mood">Mango</button>
<button type="button" class="mood">Lychee</button>
<button id="intoArr">Show</button>
I would approach it something like this:
var butTxArr = [];
// create a temporary array
var temp = [];
$("#intoArr").click(function () {
$('.mood').each(function () {
// grab the text from the mood class
var txt = $(this).text();
// loop over the data array
for (var i = 0, l = arr.length; i < l; i++) {
// use `some` to check to see if the text appears
// in any of the element, and if it does, add it
// to the temporary array
var found = arr[i].some(function (el) { return el.indexOf(txt) > -1; });
if (found) temp.push(arr[i]);
}
});
// flatten the temporary array
butTxArr = [].concat.apply([], temp);
});
DEMO
You could do something like this:
$("#intoArr").click(function(){
$('.mood').each(function(){
for (var i=0;i<array.length;i++) {
if(array[i].toString().indexOf($(this).text()) > -1) {
butTxArr.push(array[i]);
}
}
})
for (var a=0;a<butTxArr.length;a++) {
alert(butTxArr[a]);
}
});
Demo here.
You can use high order function with the .filter() method, by using the functional way. So you can create a function generator, and make your code more reusable and more cleaner.
//Create a function generator to filter our array
function filterBy(filter){
return function(elm){
return elm.join('').indexOf(filter) > -1;
}
}
var filtered = [];
$('#intoArr').click(function(){
$('.mood').each(function(){
//Retrieve text param
var txt = $(this).text();
//Filter our array by using high order function and filter method
//and push it into our filtered array
filtered.push(array.filter(filterBy(txt))[0]);
});
//Flat the result
filtered = [].concat.apply([], filtered);
console.log(filtered)
});
i want to know how can i store data in an array like that in order to do it with push function.
here is the code
var data_array = [];
and data look like that
var my_data = {
"2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
"2012":{"name":"Agents","total":1997,"drilldown":"true"},
"2013":{"name":"Coachs","total":1188,"drilldown":"true"},
"2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
"2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};
any help to change this way of inserting and use push function .
May be this will help,
You can loop through all the keys of the object and push each one into the array
var data_array = [];
var my_data = {
"2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
"2012":{"name":"Agents","total":1997,"drilldown":"true"},
"2013":{"name":"Coachs","total":1188,"drilldown":"true"},
"2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
"2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};
var keysArray = Object.keys(my_data);
keysArray.forEach(function(key, index) {
data_array.push({ key : my_data[key]});
});
console.log(data_array);
Try this (wrap data in curly braces):
data_array.push( {"2011":{"name":"Team Leaders","total":93,"drilldown":"true"} })
I don't know Exactly what do you want. Anyway, I think that It works for you.
var personInfo = new Object();
var my_data = new Object();
personInfo.name = 'Team Leaders';
personInfo.total = 93;
personInfo.drilldown = 'true';
my_data.person1 = personInfo;
my_data.person2 = personInfo;
// confirm
var jsonType = JSON.stringify(my_data);
console.log(jsonType);
I think this is what you need
var data_array = [];
var my_data = {
"2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
"2012":{"name":"Agents","total":1997,"drilldown":"true"},
"2013":{"name":"Coachs","total":1188,"drilldown":"true"},
"2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
"2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};
var data_keys= Object.keys(my_data);
data_keys.forEach(function(key, index) {
var obj = {};
obj[key] = my_data[key];
data_array.push(obj);
});
In Javascript, I have a string of options for a select tag. This is my string:
var myOptionsString = '<option id=""></option><option id="1">Self Service</option><option id="2">Administrator</option>';
In Javascript, I want to convert it to a 2-dimensional Array where 1st dimension will store the id and 2nd dimension will store the text of an option.
How can I do that? I am looking for Javascript solution; I am open to 3rd party solutions also like jQuery.
You can do it by converting the string into DOM options, then iterating over them, so:
var s = '<option id=""></option><option id="1">Self Service</option><option id="2">Administrator</option>'
function optionsAsArray(s) {
var sel = document.createElement('select');
var result = [[],[]];
sel.innerHTML = s;
Array.prototype.forEach.call(sel.options, function(opt) {
result[0].push(opt.id);
result[1].push(opt.text);
});
return result;
}
console.log(JSON.stringify(optionsAsArray(s))); // [["","1","2"],["","Self Service","Administrator"]]
You can also do it by parsing the string, but that may be more work.
Edit
You can also use the new DOMParser, but fairly recent browsers are required for support:
function optionsAsArray(s) {
var parser = new DOMParser();
var opts = parser.parseFromString(s, "text/html").querySelectorAll('option');
var result = [[],[]];
Array.prototype.forEach.call(opts, function(opt) {
result[0].push(opt.id);
result[1].push(opt.text);
});
return result;
}
The above creates an array of:
[[id0, id1, id2, ...], [text0, text1, text2, ...]]
if you want pairs like:
[[id0, text0], [id1, text1], ...]
Then the above can be:
function optionsAsArray(s) {
var parser = new DOMParser();
var opts = parser.parseFromString(s, "text/html").querySelectorAll('option');
return Array.prototype.map.call(opts, function(opt) {
return [opt.id, opt.text];
});
}
// [["",""],["1","Self Service"],["2","Administrator"]]
which can be reduced to:
function optionsAsArray(s) {
return Array.prototype.map.call(new DOMParser().parseFromString(s, "text/html").querySelectorAll('option'), function(opt) {
return [opt.id, opt.text];
});
}
I have used jQuery for the solutions below.
If you want the array to be made from DOM then you can do this
<select id="selectopt"><option id="">Select</option><option id="1">Self Service</option><option id="2">Administrator</option><option id="3">Guest</option><option id="4">Limited</option></select>
var arr = [];
console.log('====array 1===');
$('select option').each(function(){
var id = $(this).attr('id');
var value = $(this).text();
arr.push([id, value]);
console.log(arr);
});
If you need it to be made using the string then use $.parseHTML for converting the string to DOM nodes.
var arr2 = [];
var myOptionsString = '<option id=""></option><option id="1">Self Service</option><option id="2">Administrator</option><option id="3">Guest</option><option id="4">Limited</option>';
var options = $.parseHTML(myOptionsString);
console.log('====array 2===');
for (var i=0; i< options.length; i++){
var id1 = options[i].id;
var value1 = options[i].value;
arr2.push([id1, value1]);
console.log(arr2);
}
Fiddle Demo