Hello i am currently running a function in my javascript called 'save' which has the functionality of:
function save(){
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {};
var num = document.getElementById("num").value;
newItem[num] = {
"methv": document.getElementById("methv").value
,'q1': document.getElementById("q1").value,
'q2':document.getElementById("q2").value,
'q3':document.getElementById("q3").value,
'q4':document.getElementById("q4").value,
'comm':document.getElementById("comm").value
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));
and currently the format of this comes out like this:
[{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}]
is there any way i can change this to a format to something like:
{1173627548,dont know, -,-,U,-,}
Thanks
All you have to do is use an array instead of an object:
newItem = [
num,
document.getElementById('methv').value,
document.getElementById('q1').value,
document.getElementById('q2').value,
document.getElementById('q3').value,
document.getElementById('q4').value,
document.getElementById('comm').value
];
Related
I have this String:
['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
I want to get the keys 'TEST1-560' which is always fist and "car" value.
Do you know how I can implement this?
This is a very, very scuffed code, but it should work for your purpose if you have a string and you want to go through it. This can definitely be shortened and optimized, but assuming you have the same structure it will be fine.:
// Your data
var z = `['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']`;
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1,dividedVar[ind].split(":")[1].split("}")[0].length-1);
console.log(car)
}
}
console.log(testName);
output:
BLUE
TEST1-560
In a real application, you don't need to log the results, you can simply use the variables testName,car. You can also put this in a function if you want to handle many data, e.g.:
function parseData(z) {
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1, dividedVar[ind].split(":")[1].split("}")[0].length - 1);
}
}
return [testName, car]
}
This will return the variables values in an array you can use
const arr = ['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
const testValue = arr[0];
const carValue = JSON.parse(arr[1]).data[0].car;
console.log(testValue);
console.log('-----------');
console.log(carValue);
If your structure is always the same, your data can be extracted like above.
Currently I have a PHP page returning some values. The data is something like this:
08-30-2018, in
08-29-2018, out
08-28-2018, in
08-27-2018, in
How can I create a custom array in Javascript with the values above to be similar as this array below:
var system = [
['08-30-2018', 'in'],
['08-29-2018', 'out'],
['08-28-2018', 'in'],
['08-27-2018', 'in']
];
I have tried array.push, but it does not create an array like above.
What should I do? Can you help me? Thank you!
You can use multi-dimensional arrays in JavaScript
var system = [];
var output = "08-30-2018, in\n08-29-2018, out\n08-28-2018, in\n08-27-2018, in";
var items = output.split("\n");
for(i=0; i<items.length; i++){
var data = items[i].split(",");
var item = [];
item.push(data[0].trim());
item.push(data[1].trim());
system.push(item);
}
console.log(system);
You could also parse this kind of input using regular expressions:
const input = '08-30-2018, in\n08-29-2018, out\n08-28-2018, in\n08-27-2018, in';
const regex = /(\d{2}-\d{2}-\d{4}), (in|out)/g;
let system = [];
let match;
while ((match = regex.exec(input)) !== null) {
system.push([match[1], match[2]]);
}
I currently have a forEach loop like this.
var videoUrls ={};
ytplayer.config.args.url_encoded_fmt_stream_map.split(',')
.forEach(function(item) {
var obj = { };
item.split('&')
.forEach(function(param) {
param = param.split('=');
obj[param[0]] = decodeURIComponent(param[1]);
});
videoUrls[obj.quality] = obj;});
Since IE is not supporting forEach loop, I tried to convert this to for loop.
var videoUrls ={};
var typea= ytplayer.config.args.url_encoded_fmt_stream_map.split(',');
for (var item=0; item<typea.length; item++){
var obj= {};
var typeb= typea[item].split('&');
for (var param=0; param<typeb.length; param++){
typeb[param]= typeb[param].split('=');
obj[typeb[0]] = decodeURIComponent(typeb[1]);
}
videoUrls[obj.quality]= obj;
}
But when I run the script the results were different. What did i do wrong?
Thanks in advance.
it should be:
typeb[param]= typeb[param].split('=');
obj[typeb[param][0]] = decodeURIComponent(typeb[param][1]);
Because the other loop is:
param = param.split('=');
obj[param[0]] = decodeURIComponent(param[1]);
Not:
obj[item.split("&")[0]] = decodeURIComponent(item.split("&")[1])
If it's still not clear, here is a simpler explanation:
typeb === item.split("&");
typeb[param] === param;
The problem is here:
for (var param=0; param<typeb.length; param++) {
typeb[param]= typeb[param].split('=');
obj[typeb[0]] = decodeURIComponent(typeb[1]);
}
You're overwriting an element of the array you're iterating over (typeb[param]) and then using a hardcoded index into the same array (typeb[1])
Should be more like:
for (var param=0; param<typeb.length; param++) {
var arr = typeb[param].split('=');
obj[arr[0]] = decodeURIComponent(arr[1]);
}
And you cannot use library like jQuery? It is for this reason jQuery is built. If you cannot then i think this is what you need to do
obj[typeb[param][0]] = decodeURIComponent(typeb[param][1]);
How to create multidimensional array??
I tried it so far:
var post_data = [];
var id = 1;
post_data[id] = [];
post_data[id]['name'] = 'abc';
post_data[id]['date'] = '01-03-2014';
post_data[id]['country'] = 'India';
console.log(post_data);
the above code is not giving me the key. Whats wrong?
DEMO FIDDLE
i want a output something like this:
[1]=> array
(
"name": "abc",
"date": "01-03-2014",
"country": "India",
)
How to get the above output???
To get wished result you can change
var post_data = [];
to
var post_data = {};
and
post_data[id] = {};
You are trying to make an array of object.
Try this : -
post_data[id] = {};
You are using the inner array as an object. The properties that you set on the array still is there, when you display it only the array items are shown.
You should use an object instead of an array, as you are not using the array as an array:
post_data[id] = {};
Instead of setting the properties after creating the object, you can set them when you create it:
post_data[id] = {
name: 'abc',
date: '01-03-2014',
country: 'India'
};
In the third line of code you have to write
post_data[id] = new Array();
So the entire code section looks like
var post_data = [];
var id = 1;
post_data[id] = new Array();
post_data[id]['name'] = 'abc';
post_data[id]['date'] = '01-03-2014';
post_data[id]['country'] = 'India';
console.log(post_data[id]['name']);
This should fix it, best of luck :)
When I run the following javascript, it fails when input_array[input_array.length] = id; is not commented out. Can anyone see what is causing this?
function cat_images_low_lag () {
var input_array = new array ();
cat_images = $(".category-description").next().find("img");
cat_images.each(function () {
url = $(this).parent().attr("href");
id = url.split("id=");
id = id[1];
input_array[input_array.length] = id;
});
alert ("trst");
alert(input_array.join("\n"));
}
cheers!
First thing, replace:
var input_array = new array ();
With:
var input_array = new Array();
And use this to insert:
input_array.push(id);
Or directly add:
input_array[input_array.length] = id;
Other ways to initialize arrays:
var input_array = [];
Others noted the capitalization problem, but since you're using jQuery, a nicer way to build the Array is like this:
function cat_images_low_lag () {
var input_array = $(".category-description + * img").map(function () {
return this.parentNode.href.split("id=")[1];
}).toArray();
alert ("trst");
alert(input_array.join("\n"));
}
Your initialization of the array is incorrect
var input_array = new array ();
You should use the shorthand
var input_array = [];
or
var input_array = new Array();
Moreover, to avoid having cat_images be a variable in the global scope, you may want to consider scoping it locally like this
var cat_images = $(".category-description").next().find("img");