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 !
Related
JS noob here. I want to store a list of option for a dropdown in an array. I want a key to be associated with every value something like this
var newArray = [
{
key: "key",
val:({value:"val", label:"label"}, {value:"val",label:"label"})
}
]
The code above returns undefined when I try to read val. What is the solution? Thanks
var newArray = [
{
key: "key",
val:[{value:"val", label:"label"}, {value:"val",label:"label"}]
}]
The only thing i changed were parentheses () into [], because it's the thing that declares an array. Now, if you want to read the val key, you need to do this stuff.
You have an array named "newArray". It only has 1 element (which is also the first).
Now lets get the first element of the array by newArray[0]. Now you have accessed the object inside the array. Now you can read the the value by newArray[0].val. And now you have entered a new array, which elements you can read with newArray[0].val[0] and newArray[0].val[1]
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)
}};
}};
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 that contains an array of objects from which I need to get a value of their properties.
As an example this is what I need to get:
Stronghold.bins.models[0].attributes.entity.title
Which returns "Stronghold Title 1"
function grabItemName(){
var itemName=$(Stronghold.bins).each(function(){
return this.models[0].attributes.entity.title == title;
console.log(itemName);
})
};
(if there is a better way for me to ask this question please let me know)
I apologize if this was poorly asked!
The current issue is that it does not understand the array value '[0]' and cannot read it as it is undefined. What do I need to do to grab the 'title' value of all items in the array?
What do I need to do to grab the 'title' value of all items in the array?
That's what .map [docs] is for. It lets you map each value in an array to another value.
In the following I assume you want to iterate over each Stronghold.bins.models, because iterating over Stronghold.bins does not make sense with the provided information:
var titles = $.map(Stronghold.bins.models, function(obj) {
return obj.attributes.entity.title;
});
// `titles` is now an array containing `.attributes.entity.title;` of
// each object.
The current issue is that it does not understand the array value '[0]' and cannot read it as it is undefined.
Well, that won't happend anymore ;) In your example you where iterating over the properties of the Stronghold.bins object. One of these properties is models itself (!) and I doubt that any other property value has a models property.
Try using the other version of the each function:
$.each(Stronghold.bins, function () {
});
The version you are using is for looping through an element on the page, e.g $('body div p').each(function() {}), which isn't what you want in this instance: You want to loop over the values contained in Stronghold.bins.
I'm having trouble deleting/removing an item from an Array in jQuery. I've run the results in console.log() and it shows up as an Object. I've created a function which returns a json string and then I parses it, an example below:
var ret = jQuery.parseJSON($.return_json(data));
It works nicely, however, I am running an $.each loop which removes items from that array/object.
var old = $("element").find("li[rel=item]");
$.each(old, function(index, value) {
ret.splice($(value).attr("id"), 1);
});
Above, I am searching for elements with attribute rel = item. The same element contains an id which is related to the index of the function which returns the json parsed variable.
I ran Developers Tools in Google Chrome to see the error and it prints:
Uncaught TypeError: Object #<Object> has no method 'splice'
Any words of guidance will be much appreciated. Thanks.
It seems like ret is not actually an array (and likely an object (ex: {someName: "someVal"}) instead).
I'm also making an assumption that you mean for $(value).attr("id") to be a string identifier like someName in the object example above. If that is the case and you are working with an object and you do have the appropriate property identifier, then luckily there is an easier solve than splice.
Try:
$("element").find("li[rel=item]").each(function() {
delete ret[$(this).attr("id")];
});
splice is only a method of arrays, not objects. ret in this case, is an object, not an array.
If you are trying to remove specific elements from an object, you can do this:
$("element").find("li[rel=item]").each(function(i,v){
delete ret[v.id];
});
ps. You can use .each instead of $.each.
If you really want to make the object into an array, you can simply loop through it and push the elements into an array.
var obj = {"1":"item 1", "2": "item 2", "3": "Item 3"};
var arr = [];
for(i in obj){
if(obj.hasOwnProperty(i)){
arr.push(obj[i]);
}
}
ret is the JSON object containing the array, and you can't splice it. You need to reference whatever you called the array within the object and splice that.
(Would help if you posted the code where you define the array).