How do I access these elements of this JSON-encoded javascript? - javascript

I have an array in PHP that I encode to json:
$jsonOutput = json_encode($output);
Then in my javascript, I use this to parse it:
var jsonOutput = JSON.parse('<?php echo $jsonOutput; ?>');
My output looks like this in the Chrome console:
Ultimately, I have two arrays, and I'm trying to write a compare between the two to show if there are any items in the first array that aren't in the second, but I'm not sure how to reference red and orange here.
I tried console.log(jsonOutput[0]) but I get undefined.
Also, as a side note, does anyone have any good resources for reading up on arrays in javascript and all their ins-and-outs? It seems to be one aspect that I'm struggling with lately...

The problem is that your jsonOutput is an Object, so in order to access one member of the object you either have to user jsonOutput.red/jsonOutput.orange or jsonOutput["red"], jsonOutput["orange"] to access a member of the object.
More info here Access / process (nested) objects, arrays or JSON.

jsonOutput.red[0]
You have an object with two keys. Not an array.

You access those arrays using:
jsonOutput.red;
jsonOutput.orange;

Related

How to parse the following json string into an object?

var jsonString = '{"DeviceId":3,"results":{"1":"[{\"x\":513,\"y\":565,\"width\":175,\"hight\":208}]"}}';
var message = JSON.parse(jsonString);
I got an error saying Unexpected token u in JSON at position 0
at JSON.parse.
Could you please guide me what's wrong?
THanks in advance!
At the last few characters looks wrong. The :212 has no sense as the value (that long array) for key "1" was already set, so that later :212 looks weird
Also enclosing it in single quotes it makes that all be like a huge string, and not as an array structure.
See Results key as value contains a sub array which contain "1" key which as value contains a string enclosing another json array (but escaped as plain string, so no structurally accesible for the main object . But that string if post -processed the :212 is paired to what? , no key, no comma neighter , to the precedent whole array which already was the value, not the key?. Anyway weird.
In your JSON string, there is wrong something with ":212", as it's not valid JSON, because it doesn't have any property that it's mapping the value for. For example, you are mapping values for width and height with properties keys. But for "212", there is no property.
Here is the above JSON formatted:
var jsonString = '{"DeviceId":"3","results":{"1":"[{\\"x\\":513,\\"y\\":565,\\"width\\":175,\\"hight\\":208}]"}}'
var message = JSON.parse(jsonString);
If you want to format the results, you can do to it, there is no error on it:
JSON.parse(message.results['1'])
Here is the JS Bin link for above code: https://jsbin.com/fiyeyet/edit?js,console
Just an advice
Professional code is all about proper spacing, proper identation , proper commenting, don't try to write down all within one single line, structure it VISUALLY nice to see nice to read nice to comprehend, and you will be approved in most jobs.
Hint: declare a normal array/object , convert it to json string using the proper function, then use the string variable returned by the function to test your code or whatever doing. That way, you can write down in the source really nice the structure.

How do you access multi-dimensional arrays of objects in JavaScript?

I need to access JavaScript objects stored in a multi-dimensional array. The data is being exported by a WordPress plug-in. Note, I cannot change the code to use a single array.
There are two arrays named "employees". Is this array format compatible with JavaScript? The JSON export was intended for PHP processing.
(Note, The code below is a simplified model to illustrate the issue).
var data = '{"employees":[{"firstName":"John0"}, {"firstName":"Anna0"},{"firstName":"Peter0"}],"employees":[{"firstName":"John1"}, {"firstName":"Anna1"},{"firstName":"Peter1"}]};';
var json = JSON.parse(data);
document.querySelector('#test').innerHTML = json.employees[2].firstName;
Here it is on JSFiddle:
https://jsfiddle.net/2524fhf4/11/
How for example, would one access the value "Peter0" in the first array? In a single array, it would be accessed like this:
var result = json.employees[2].firstName;
It appears to me that in this format it is only possible to access the last array.
It appears to me that in this format it is only possible to access the
last array.
Because when your object literal has two (or more) keys of the same name, last one will override the rest of them.
Check this demo
var data = '{"employees":[{"firstName":"John0"}, {"firstName":"Anna0"},{"firstName":"Peter0"}],"employees":[{"firstName":"John1"}, {"firstName":"Anna1"},{"firstName":"Peter1"}]}';
console.log(JSON.parse(data)); //it will only display first one
In the above example, you can see that there is only one key of the data

Javascript array/object order from associative PHP array

Before I describe the issue, please forgive any incorrect terms and accidental references to objects instead of arrays and vice-versa, I'm not completely up to speed on this but working my way through it.
I have the following array in PHP saved as a session variable:
{"CategoryF":[],"CategoryA":["Life","There","People","Land","Family"],"CategoryC":["Various"]}
After a thumbnail in a grid of images is dragged into a new order, it execute a function in javascript and makes a call to a PHP script using ajax. It currently only retrieves the most up to date version of a session array. It will later progress to make the necessary steps to save the updated array back to session variable and database:
var sorty = Sortable.create(thumbcontainer, {
animation: 250,
draggable: "img",
dataIdAttr: 'id',
onUpdate: function (/**Event*/evt) {
var orderList = sorty.toArray();
var catsArray =
$.ajax({
type: 'POST',
url: 'includes/proc_cats.php',
dataType: 'json'
}).done(function(returnedCatsArray) {
console.log(returnedCatsArray);
});
console.log('Dragged. Order is: ' + orderList);
}
});
proc_cats.php
<?php
// Access the existing session
session_start();
// $catsArray is a session variable, in the format as above.
$catsArray = json_encode($_SESSION['categoriesPics']);
echo $catsArray;
?>
The var orderList will produce a string with the order of each thumbnail by id, separated by comma: '42,35,95,12,57'.
The console shows the PHP array as a javascript array fine but in a different order. I want to be able to insert the string containing the orders into the array and save it back into the database. It will associate with its relevant category, similar to:
{"CategoryF":[],"CategoryA":["Life":["23,74,47,12,86,83,12"],"There","People","Land","Family"],"CategoryC":["Various"]}
But can't lose the order as other parts of the site reference the array by indices using array_keys. The console produces:
Object:
CategoryA:Array[0]
CategoryC:Array[0]
CategoryF:Array[5]
Have I missed something? I believe that the overall array is an object rather than an array because it didn't have any index whereas the subcategories did and they get presented as an array. array_keys in PHP have made it straightforward enough to work around any indexing problems up until now on the PHP side in other areas of the site but I'm wondering if the solution for the javascript side is something as straightforward? The subcategories currently have indices only because I've yet to associate and orderList with them so I'm not trying not to backtrack and build an index for the array as it's going to get difficult (unless there's a simple way to do this that I've overlooked).
(This is a more specific version of a question I asked an hour ago that I've now deleted for being too broad).
I believe you have a slight confusion based on the terms 'associative array' and 'array'. A php associative array corresponds to a javascript object. returnedCatsArray should be accessed similar to $catsArray. ie. with keys. If one of those keys returns an an actual array, you can then index into it.
php array_keys would be Object.keys(returnedCatsArray) in javascript.
From further research it appears this is just not doable. So the best way to do this may be to provide an order array alongside my category array.
If I add the additional code of:
$parentCatOrder = array_keys($catsArray);
in my proc_cats.php script I have a concise way of generating an index reference for my original array on the fly each time. This produces an array similar to:
$parentCatOrder = {'categoryF', 'categoryA', 'categoryC'};
which has an index that I can refer to that keeps its order. So $parentCatOrder[2] will always produce 'categoryC' unless I've changed the array myself.
I then return both arrays to javascript using the following:
$return_data['catsarray'] = $catsArray;
$return_data['parentcatsorder'] = $parentCatOrder;
// Encode it back into a JSON object before sending
echo json_encode($return_data);
In javascript I can reference returnedCatsArray.catsarray[returnedCatsArray.parentcatsorder[1]][3] if I'm working with an index of 1-3 and guarantee this will produce the same result for every user unless the array has been changed by the user.

Get Data from Text File to Multidimensional Array Javascript

I have a little bit of an issue with a JavaScript function that needs to read data from a TextFile (something JS is already limited with) and then process tha TextFile data into a MultiDimensional Array (another thing that JS doesn't nativelly suport).
With that in mind, I have a text file in this format:
1, Name, Data, Serial
2, Name, Data, Serial
3, Name, Data, Serial
And so on.
So, the objective is to get that same data and put it, like that, into an array.
I suppose that, from what I've been reading, I need an Array of an Array, segmenting the first one by lines [/n] and the second one by commas [,]. However, given the "by-default" limitations, I'm very confused at this point. I do suppose I need jQuery, however.
I tried this:
var fs = require('fs');
var array = fs.readFileSync('file.txt').toString().split("\n");
for(i in array) {
var array = fs.readFileSync('file.txt').toString().split(",");
for(f in array) {
}
}
With little success, because then I don't really know how to store it, the objective being a Multidimensional Array that Replicates the Format of the text file, so latter it could be used to search by index or instance following an user input to get results.
I really appreciate any help.
At first glance it seems like you are trying to read in a CSV file. If that is indeed the case I recommend node-csv:
http://www.adaltas.com/projects/node-csv/
https://github.com/wdavidw/node-csv
This helped me reading file to JavaScript, however this example converts retrieved data to JSON. Just looking at the format of your text file, I would assume a JSON string or Javascript object would work with your data.
Example convert to JSON
With JSON and JS objects, instead of referencing a array indexes eg. array[i][x]. you would replace [x] with .propertyName
data = {
"id": 1,
"name": "Fred"
};
//access data like this
data[i].name //will return "Fred" as i =0
to create JS object, just initialize array properties without the ""(quotation marks). accessing JS and JSON properties are done in the same way, main advantage over a multidimensional array is that you can reference an actual property name, as opposed to indexes.

javascript why I could not get the name of file from files array?

I have simple javescript about input|file object:
var upfiles=new Array();
function addfile(files){
upfiles.push(files);
alert(upfiles[0].name); //undefined
alert(files[0].name); //can get file name
upfiles[0].prop("name"); //can get file name
alert(upfiles.length); //1
}
I don't know why the upfiles[0].name only give me return undefined, while the upfiles[i]).prop("name") work. the different between two method?
Did you try
upfiles[0][0]
Seeing as you push an array of files into another array etc.
You probably want to use concat rather than push here, to create a one-dimensional array.
I wish I can just comment...
I'd try this in chrome, and put
console.log(upfiles);
before your alerts... And just examine the structure of the object in the console.
When I worked with a framework that doesn't have detailed documentation, I had to examine their function outputs like that a lot.

Categories

Resources