I'm working on a (JavaScript/JQuery) project that requires me to save data as a file.
The data being stored is an array, which normally wouldn't be an issue because I can would just store it as a string and then split the string based on "," on loading the data again. However the array I need to store is an array of other arrays of data, some of which have a few layers of arrays.
My initial thought is to run a function which converts each array to a string starting at the lowest levels and then add some sort of identifier (eg '/////') between each entry to separate each array of data and use them as the thing to detect for a Split function. This however make the storing/loading of the data very complex and I was wondering if there is a better way of saving multi-layer array data in Javascript.
You can still save it as a string but the serialization should be something like JSON.
To convert to json (encode) use JSON.stringify. This returns a string that you can save to the file:
var json_string = JSON.stringify(my_array);
Afterwards, to decode the string in the file (after reading it) use JSON.parse
var my_array = JSON.parse(json_string);
You can use JSON.stringify to convert a multi-level array to a string. And then you can use JSON.parse to convert it back to an array. Once you have the string you can save and restore it and use these methods to re-create the array.
a = [1, 2, [3, 4, [5, 6, [7, 8], 9]]]
> [1, 2, Array[3]]
s = JSON.stringify(a)
> "[1,2,[3,4,[5,6,[7,8],9]]]"
a2 = JSON.parse(s)
> [1, 2, Array[3]]
Related
I would like to change the url request while clicking on a link one of the element of an array. For example :
?foo[]=1&foo[]=2
to
?foo[]=1&foo[]=3
I use URLSearchParams with methods .getAll('foo[]') and then .set('foo[]', array)
Finally, I use jquery method param() to generate a correct url string (as I was not able to use URLSearchParams.toString() with an array -- the result is always foo[]=1&3).
This is working, but if I had other parameter in the request I would like to keep, it becomes complicated to regenerate the url.
For example :
?foo[]=1&foo[]=2&bar=3&bar[]=4&page=1
to
?foo[]=1&foo[]=3&bar=3&bar[]=4&page=1
I have many parameters, so I would like to avoid the rebuild the entire query object to pass to $.param(). So :
Is there any option to get the whole array from URLSearchParams without using any loop.
Is there any trick to use URLSearchParams.toString() with arrays.
What you'll need to do is remove the foo[] entry, then iterate the values array from .getAll('foo[]') and .append().
For example
const usp = new URLSearchParams([
['foo[]', 1],
['foo[]', 2],
['bar', 3],
['bar[]', 4],
['page', 1]
])
console.info('original:', decodeURIComponent(usp.toString()))
// get all 'foo[]' entries
const foos = usp.getAll('foo[]')
// incremenent the last value
foos[foos.length - 1]++
// remove 'foo[]'
usp.delete('foo[]')
// iterate values and append
foos.forEach(foo => usp.append('foo[]', foo))
console.info('updated:', decodeURIComponent(usp.toString()))
Is there any method to remove unnecessary spaces of output array. When I run the code there is space in between comma and integer and also integer and bracket.
var arr = [1,2,3,4,5];
console.log(arr);
output
[ 1, 2, 3, 4, 5 ]
desire output
[1,2,3,4,5]
console.log or console.log is a basic tool function which have very defined behavior that you can't change.
The only thing you can do is to use a trick. console.log handle differently the string and the arrays, so you can transform your array before to display it.
Moreover they didn't made it possible to influence the display because there is no purpose to it. What are you trying to achieve using console.log in your app?
console.log had been created in order to display debug messages, not to display data to regular users.
For example in node.js, in order to display data to your user in console, use of :
process.stdout.write(your_string_in_your_own_format);
const arr = [1,2,3,4,5];
// Basic array
console.log(arr);
// Transform the arr into a string
console.log(JSON.stringify(arr));
Using jquery.nestable.min.js, I get a the following output:
[{"id":32},{"id":29},{"id":30}]
This current output is coming from the following code:
const myList = JSON.stringify(list.nestable('serialize'));
I need it to simply be:
32, 29, 30
End result is that I would like to read a normal array in PHP. I'm looking to either convert myList to an array in Javascript and POST that array, or convert the current version of the object to an array inside PHP, whichever is most effective.
I've tried to use json_decode in PHP, but I get empty values. So I figured if I can just convert to a normal Array before sending it off to PHP, then it would be less of a hassle.
Thank you.
This may be duplicated, in which case, please point me to the best answer
Depending on whether you want an array (per your title), or literally 32, 29, 30 per your post:
console.log([{"id":32},{"id":29},{"id":30}].map(i => i.id))
console.log([{"id":32},{"id":29},{"id":30}].map(i => i.id).join(', '))
Which, with your example, is probably going to be:
const myList = JSON.stringify(list.nestable('serialize').map(i => i.id));
If you just want an array of numbers, convert that output array of objects to array of numbers
var list = [{"id":32}, {"id":29}, {"id":30}];
var required = list.map(item => item.id);
console.log(required);
I use basic array to make reference to icons like this:
{name: "text", avatar: srcs[15]}
This works great, but now I dynamically create an array from my json api and it gives me array of objects like this:
{name: "text", avatar: "srcs[15]"}
so I cannot reference to my avatars now. How can I remove double quotes to get my array work again?
Please note that I don't want to get the srcs[15] value to the array, just make a reference to the source array.
The JSON data format does not support references. What you want it not possible.
You need to either:
Put the data you want there explicitly (this may involve duplication) or
Describe the relationship in a way that the program consuming the JSON can interpret as a reference. You could use the reviver argument of JSON.parse to inflate the description back to the data you want to point it to.
JSON is self-contained static data, and it can't reference named variables or objects outside of its own structure.
You can do it like this instead:
{ "name": "text", "avatarIndex": 15 }
And then do one of these to use it:
var avatar = srcs[data.avatarIndex]; // Avatar object in separate variable
// or
data.avatar = srcs[data.avatarIndex]; // Avatar object added into data
You should just put either the value or the whole array , you have also to read about what format json support here
Here's my suggested solutions
var array = [1, 2, 3, 4, 5, 6]
var json1 = {
name: 'test',
value: array
}
console.log("solution 1 :" + json1.value[2])
var json2 = {
name: 'test',
value: array[2]
}
console.log("solution 2 :" + json2.value)
I've seen lots of articles on how to serialise arrays from javascript to send to PHP files which the PHP file will then deserialise back into an array, etc...
I have a large-ish nested associative array in my javascript which I need to save to a string and at a later date retrieve and convert back into a string in javascript. No other program will ever touch this. It may be handy if the serialised data is human-readable but it is absolutely not a requirement.
There is an intermediate PHP file but it's only 4 lines long: all it does is save the string to a file and send it back when requested. I'm not interested in parsing the array in PHP.
What is the fastest and simplest way to convert a multi-nested associative array in javascript to a string and back again?
JSON is a subset of the JavaScript language that is widely used as a serialization format, both for JavaScript and increasingly for other languages as well. It's human-readable, except that most implementations remove optional whitespace, which makes it a bit more difficult.
Modern browsers have JSON support out-of-the-box, for older ones you will need to include a library like json2.js.
To serialize, you use the JSON.stringify method.
var myObject = {a: 2, b: 3, c: [1, 2, 3]};
var serialized = JSON.stringify(myObject);
// serialized == "{"a":2,"b":3,"c":[1,2,3]}"
To unserialize, you use the JSON.parse method.
var recovered = JSON.parse(serialized);
Well, I have constructed my array like: var data = new Array(); data["John"] = "John Smith";
Ah, this is a problem. A JavaScript Array isn't meant to be used as an associative array, it's meant as a normal zero-indexed non-associative array. You can assign properties (key/value pairs) to any JavaScript object, which is why your code is working, but the fact thay your object is an Array is probably going to cause problems. If you just create a new Object() instead things should work better.
You'll want to serialize your array into JSON:
serialized = JSON.stringify(myobject)
To get it back
myobject = JSON.parse(serialized)
http://www.json.org/js.html
var someArray = [];
someArray.push({someObjectProperty: 'someValue' });
someArray.push({someObjectProperty: 'someValue2' });
console.log(someArray);
var stringVersion = JSON.stringify(someArray);//You can save the string version anywhere...
console.log(stringVersion);
var someNewArray = JSON.parse(stringVersion);
console.log(someNewArray);
Everyone has explained this well on the Javascript side, but this is how it happens on the PHP side:
<?php
$arr = Array(1, 2, 3, 'a', 'b', 'c'); // an array in PHP
echo json_encode($arr); // output the array as JSON: [1,2,3,'a','b','c']
?>
<?php
$json = "[1,2,3,'a','b','c']"; // a JSON string to be parsed by PHP
$arr = json_decode($json); // this is our original array in PHP again
?>