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)
}};
}};
Related
I'm using Retool and looking up records in a Firestore table by a Document ID.
The below code works great and returns an array of JSON objects. However it does not have the appIDs[?] used in the lookup. How can I add the appIDs ('id1','id3', or 'id2') as an additional element to the matching JSON object in the array? The order of the returned array of JSON objects is not necessarily the same order as the appIDs array.
var appIDs = ['id1','id3','id2'];
var metadatas = appIDs.map(row => {
return qTile_description_v1.trigger({
additionalScope: {
appID: row
}
});
});
return Promise.all(metadatas.map(p => p.catch(error => null)));
Answer in comments.
Apparently the answer is easy since my statement that the order returned may not be the same as the order of the keys in the array is false. The order will be the same, so problem solved.
I am just unable to figure out a way of creating, a list of objects, inside an array, and they should not have any index attached to them.
let allConditions = []
for (let i = 0; i < 3; i++) {
allConditions.push({
datasource: 'datasourceName',
column_name: 'columnName',
id:i
})
}
console.log(allConditions)
This gives me a result like:
And this is what I need:
What am I doing wrong ? The console log I am getting in the snippet is what i want, but that's not what you will get if you copy my code and use it in Google chrome's console. Same goes for my code, I get 2 rows with indexes 0 and 1, which is expected as I am using .push method. What else should I do get an array, which can hold many similar objects, but have no key.
UPDATE: To the people answering that indices will always be there, even if I don't use one, I am sending this data to a backend api, and it rejects my request because it does not find an 'array of objects. So I am not sure what I should do.
Arrays will always have indices, although you don't have to use them. Even if you created your array manually outside the loop, it would have indices.
The 2 are equivalent, the keys or array indexes are always there.
Update: This code just works :) Other logic in my page caused a problem
I'm reading out a JavaScript object from a jQuery data object:
$('body').data('myvals', {var1:"lorem",var2:"ipsum",var3:"dolores",var4:"amet"});
var obj = $('body').data('myvals');
I can successfully access the contents of this object
console.log(Object.entries(obj));
This returns (in Firefox console):
[["var1", "lorem"], ["var2", "ipsum"], ["var3", "dolores"], ["var4", "amet"]]
But I don't succeed in retrieving a specific property (getting 'lorem' by accessing 'var1'). Following attempts return undefined:
console.log(obj.var1);
console.log(obj[var1]);
What am I doing wrong?
this works just fine, I don't see what's the problem: DEMO
$('body').data('myvals', {var1:"lorem",var2:"ipsum",var3:"dolores",var4:"amet"});
var obj = $('body').data('myvals');
console.log(obj.var1);
console.log(obj['var1']);
if the code above doesn't work try console.log($('body').data('myvals')); and see if it returns any value.
if it returns undefined then you've probably forgotten to use document ready, just try wrapping your code in $(function(){ ... })
You can access the entries returned as pairs from Object.entries using destructuring as below:
Object.entries(obj).forEach(([key, value]) => {
console.log(key);
console.log(value);
})
An alternative way to iterate using for-of loop
let obj = { one: 1, two: 2 };
for (let [k,v] of Object.entries(obj)) {
console.log(`${k}: ${v}`);
}
This :
[["var1", "lorem"], ["var2", "ipsum"], ["var3", "dolores"], ["var4", "amet"]]
is an array with indexes as keys.Its is not an Object (Even though in Javascript pretty much everything is an Object) So when you try obj.var1 you will get undefined.
Cause there is no obj.var1 in there. There is obj[0] which holds array("var1", "lorem"); inside it.
This :
{"var1":"lorem"}, {"var2":"ipsum"},{"var3":"dolores"},{"var4":"amet"}
is an Object , in this one if you type console.log(obj.var1) you will get "lorem".
You added more code since i replied so i knopw need to change my annswer.
Your issue is "Object.entries()" , this will return an Array , you need to use
Object.keys(obj) .forEach(function(key){
console.log(key);
});
Addition
Your question layout and provided info have been a bit confusing.
Avoiding what you wrote at the start and focusing only on your last addition to your question , your only error is the:
console.log(obj[var1]);
it should be
console.log(obj["var1"]);
Other than that it should work as expected.
Instead of printing Object.entries(obj) to the console, it would be clearer for you to print the object itself to the console. The entry list is a distraction from the issue you're dealing with. What I mean is this:
var obj = $('body').data('myvals');
console.log(obj);
//or this
console.log(JSON.stringify(obj));
That will show you the actual content of the associative array. From there, either of these should work. Don't forget to use string quotes for the array index:
console.log(obj.var1);
console.log(obj["var1"]); // obj[var1] is incorrect, need quotes
If you see "var1" as a key in the full object printout above, then individual property should also be shown here. Otherwise, some other part of your code must have made changes to the content of obj or $('body).data('myvals') by the time you extract "var1"
I have an object with key value pairs inside an array:
var data = [
{
"errorCode":100,
"message":{},
"name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
"value":"2"
}
];
I want to get the value of "value" key in the object. ie, the output should be "2".
I tried this:
console.log(data[value]);
console.log(data.value);
Both logging "undefined". I saw similar questions in SO itself. But, I couldn't figure out a solution for my problem.
You can use the map property of the array. Never try to get the value by hardcoding the index value, as mentioned in the above answers, Which might get you in trouble. For your case the below code will works.
data.map(x => x.value)
You are trying to get the value from the first element of the array. ie, data[0]. This will work:
console.log(data[0].value);
If you have multiple elements in the array, use JavaScript map function or some other function like forEach to iterate through the arrays.
data.map(x => console.log(x.value));
data.forEach(x => console.log(x.value));
data is Array you need get first element in Array and then get Value property from Object,
var data = [{
"ErrorCode":100,
"Message":{},
"Name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
"Value":"2"
}];
console.log(data[0].Value);
Try this...
Actually Here Data is an array of object so you first need to access that object and then you can access Value of that object.
var data = [
{
"ErrorCode":100,
"Message":{},
"Name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
"Value":"2"
}
];
alert(data[0].Value);
what you are trying to read is an object which an element of an array, so you should first fetch the element of array by specifying its index like
data[0] and then read a property of the fetched object, i.e. .value,
so the complete syntax would be data[0].value
Hope it helps !
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.