I'm having a some trouble with the concat function in javascript. As far as I can tell, I'm using it correctly, but it's not successfully concatenating the array "value" from the JSON onto the array "currentAbilities":
$.each(ABILITIES, function(key,value) {
if(key==raceName||(key==className&&(!isAcolyte)))
{
document.getElementById('abs').innerHTML = value[1];
currentAbilities.concat(value);
}
})
The innerHTML setting line shows that the array "value" does exist. Any idea why I'm failing to concat? Value of course comes from a JSON, could that have anything to do with it? I'm afraid I only recently became familiar with $.each and JSON usage and may be doing it wrong.
Assuming the JSON has been parsed, you need to keep a reference to the new Array created by concat() because the .concat() method does not modify the original...
currentAbilities = currentAbilities.concat(value);
Or just use .push with .apply if you want to modify the currentAbilities array...
currentAbilities.push.apply(currentAbilities, value)
Also, make sure your raceName and className variables are what you expect.
Related
Can't really figure out why I cant get the values that I have passed through an AJAX call in my javascript function.
As seen in the picture, msg is the array that's passed from the backend to the javascript function
I've tried both
info['taxarray'].forEach() and info.taxarray.forEach()
Console.log(info.taxarray) works fine and it outputs the array in the console, but when I try to run iterations through this array, I can't access the values in it, I'm sure I'm missing something, but I can't figure out what it is.
This is the output for the console
You can flatten the multidimensional array with flat method:
info.flat().forEach(item => console.log(item.tax))
Using flatmap it gets even more straightforward
info.flatMap(item => console.log(item.tax))
As i can see, your info.taxarray is a multidementional array so that's every element inside it is also an another array.
your console.log(info.taxarray) gives see :
[Array(1), Array(1)]
to access tax_values of the first element you have to write info.taxarray[0][0].tax_values so that means you have to iterate the taxarray and also it's elements (which are arrays too) .
Check your code.
you can also refer to the solution of Mike Ezzati it help a lot
the response you get seems to be multidimensional (an array of arrays each of which has only one element)
info.taxarray.forEach(msg) { (item) => {
console.log(item[0].tax_values)
}};
OR if array elements can be more so iterate again
info.taxarray.forEach(msg) { (item) => {
item.forEach(msg) { (item) => {
console.log(i.tax_values)
}};
}};
I have a variable :
var testData;
And I have a function that populates an array. Goes through an array and makes another array like so :
var person = {
"Name": obj.Name,
"Age": obj.Age,
}
partsObject.push(person);
I then want to make this array into JSON so I can use it with my D3 objects, so I do this :
testData = JSON.stringify(partsObject);
I can console log this variable, but when trying to go through it via D3's forEach method like so :
testData.forEach(function(d) // data is the JSON
{
I get the error Uncaught TypeError: testData.forEach is not a function
I don't understand how I can log the variable to the console yet it's as if I can't use it as JSON. Any ideas ?
As the name suggests stringify() converts a JavaScript object (the JSO in JSON) into a string of JSON. You can console.log() it because console.log expects to take a string, and anything that's not a string is converted to one to be displayed.
If you want to use it as an array again, you need to parse your string of JSON back to the JavaScript object: JSON.parse(testData).
You really dont need to stringify your Array to pass to d3. Do not to get confused with javascript objects, since forEach requires an array to loop through and you are passing a string to manipulate with forEach function
use:
partsObject.forEach(function(d)
{
...
JSON.stringify(partsObject); creates a string as"{'Name':'ABC','Age':23}"
Uncaught TypeError: testData.forEach is not a function caused because javascript was not able to find an Array
.stringify() turns a Javascript Object into a string. You would want to either run
partsObjects.forEach()
or alternativily you could turn the stringify'ed string back into an object with
(JSON.parse(testData)).forEach()
You are currently trying to loop through a String since you stringify your array.
Just do partsObject.forEach and don't stringify your Array.
I know this isn't the best way to do it, but I have no other choice :(
I have to access the items in JSONObject by their index. The standard way to access objects is to just wirte this[objectName] or this.objectName. I also found a method to get all the fields inside a json object:
(for (var key in p) {
if (p.hasOwnProperty(key)) {
alert(key + " -> " + p[key]);
}
}
(Soruce : Loop through Json object).
However there is no way of accessing the JSONfields directly by a index. The only way I see right now, is to create an array, with the function above, get the fieldname by index and then get the value by fieldname.
As far as I see it, the p (in our case the JSON file must be an iteratable array to, or else the foreach loop wouldn't work. How can I access this array directly? Or is it some kind of unsorted list?
A JSON Object is more like a key-value-map; so, yes, it is unsorted. The only way to get around is the index->property name map you've already mentioned:
var keysbyindex = Object.keys(object);
for (var i=0; i<keysbyindex.length; i++)
alert(object[keysbyindex[i]]);
But why would you need these indexes? A unsorted map also has no length property, as an Array had. Why don't you use the for-in-loop
var counter = 0; // if you need it
for (var key in object) {
alert(object[key])
counter++;
}
? If you have a parsed JSON object, i.e. a plain JS Object, you won't have to worry about enumerable prototype properties.
Based on Bergis anserwer this is my solution:
var keysbyindex = Object.keys(this);
alert(this[keysbyindex[index]]);
return this[keysbyindex[index] || ""];
However, I think (not tested) it's extremly bad regaring performace and shouldn't be used! But desperate times require desperate measures.....
I don't think you can actually achieve this without creating your own parsing of JSON. You're writing that you want to go trough a JSON-object, but what you're actually trying to do is go trough a plain old Javascript object. Json is simply a string-representation used to transfer/store said object, and in here lies the main problem: the parser that transforms the string into an actual object (ie. the browser in most cases) can chose to ignore the order it finds the properties if it want to. Also, different browsers might have different approaches to parsing JSON for all you know. If they simply use a hash-map for the object that it's simple to loop through it, but the order won't be dependent on the order of the keys in the file, but rather the keys themselves.
For example, if you have the json {"b":"b","a":"a"} and do the for in loop, under some implementations you might end up with a comming first, and in others you might end up with b.
var jsn = {keyName: 'key value result come here...'};
var arr = jsn ? $.map(jsn, function (el) { return el }) : [0];
console.log(arr[0])
$('.result').text(arr[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="result"></span>
jQuery has the .map() function which takes as input either an array or an object but can only output an array.
It seems there are plenty of times when you want to output something more like an associative array so is there another function in jQuery that can output a JavaScript Object?
(I'm pretty sure I've used something like this in another programming language, possibly Perl.)
You can get the same result by declaring the object first, then building it out in the .map() function instead of returning the data.
This example gets all the checkboxes on the page and creates an object out of their ids and values:
var result = new Object();
$(':checkbox').map(function() {
result[this.id] = this.value;
});
result = jQuery.parseJSON(result);
for(var k in result)
{
alert(k);
alert(result[k]);
}
This code is working just fine.
But let's suppose I'm receiving object of the following type
status='FALSE'
message='error'
If you want to echo all this things first code is ok. It will alert everything.
But what If I want to work with this data, do some manipulations. In this case this for loop is a bit bad idea for me. So I have to transform probably this data into something new. Maybe constract some array during this loop and then read from array ? I think there must be some simple way to get access to that data. Please help
If result is JSON data, you should be able to simply do:
result = jQuery.parseJSON(result);
alert(result.status);
alert(result.message);
pareJSON turns the JSON data into a JavaScript Object. To access properties of an Object in JavaScript, you need to use dot notation.