Retrieve property from JavaScript object - javascript

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"

Related

JSON.stringify(list) shows an array of strings, however, Array.isArray(list) is false

I am currently trying to debug the issue in the title.
Here's some additional information:
I am receiving the list from a DynamoDB set.
JSON.stringify(list) prints: ["elt1","elt2"]
Array.isArray(list) === false
list.map is undefined, list.forEach is undefined
const list2 = JSON.parse(JSON.stringify(list))
Array.isArray(list2) === true
I have tried the above hack, and it does solve the issue- but it is definitely not conventional.
You've made an erroneous assumption: just because something produces an Array when run through JSON.stringify() does not necessarily mean it in itself is an Array to start. Consider this example:
class MyClass {
toJSON() {
return ['a', 'b'];
}
}
const list = new MyClass();
console.log(JSON.stringify(list));
console.log(Array.isArray(list));
console.log(list.map);
console.log(list.forEach);
In other words - it's entirely possible for a class to override the toJSON() method and fundamentally alter how it is processed by JSON.stringify(). I would suspect what you're encountering is that list is not really an Array (as you allude) but rather some other type that behaves this way when being stringified.
It's return valid output (list.map is undefined, list.forEach is undefined),t because JSON.stringify() convert into a string and you can't apply any array function on in it.

Javascript get value from an object inside an array

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 !

JSON.stringify turned the value array into a string

I have a JS object
{
aString:[aNumber, aURL]
}
JSON.stringify() returns
{
"aString":"[number, \"aURL\"]"
}
I thought that valid JSON can have arrays as values. Can I have stringify return the JSON string without converting the array into a string? Basically I need turn the whole JS object straight into a string, without any modification.
Is there a better way to do this? I've been looking around but everyone suggests using JSON.stringify if I want an object to string, and no one has raised this problem.
EDIT: Thanks for the quick responses. Here is how I created my JS object, please let me know if I messed up and how!
cookie = {};
// productURL is a string, timer is a number, imageSrc is a URL string
cookie[productURL] = [timer, imageSrc];
// then, I just stringified cookie
newCookie = JSON.stringify(cookie);
If it is also relevant, I am setting an actual cookie's value as the resulting JSON string, in order to access it in another set of functions. Setting the cookie's value does do some URI encoding of its own, but I've actually been grabbing the value of newCookie in the Chrome console as well and it also returns the Array as a string.
If an object you're trying to stringify has a toJSON function, that will be called by JSON.stringify. Most likely you have an external library that's adding Array.prototype.toJSON.
For example, an old version (1.6) of Prototype JS will "conveniently" add that for you.
Prototype 1.6.1:
alert(JSON.stringify([1, 2, 3]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.6.1/prototype.min.js"></script>
Whereas a newer version will not.
Prototype 1.7.2:
alert(JSON.stringify([1, 2, 3]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.2/prototype.min.js"></script>
You could try deleting Array.prototype.toJSON just to see if that's what's causing the problem. If it is, you might want to look into upgrading/deprecating any libraries in your code that do weird things like that.
Prototype 1.6.1 (after deleting toJSON)
delete Array.prototype.toJSON;
alert(JSON.stringify([1, 2, 3]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.6.1/prototype.min.js"></script>
Based on your description this is not what should happen.
If you have code like this:
var obj = {
aString:[123, "test"]
}
document.getElementById("out").value = JSON.stringify(obj);
it will generate the expected json:
{"aString":[123,"test"]}
also see https://jsfiddle.net/zudrrc13/
in order to produce your output the original object would have to look something like:
var obj = {
aString:"[123, \"test\"]"
}

JavaScript Unexpected Behaviour iterating arrays inside arrays

I'm trying to build a key/value relationship for an ajax based web app. I've decided to use a pure array-based approach as iterating arrays is faster than objs (or so I'm told).
The base of the idea looks like this:
var keyVals = [
[ "key1", ["value1"] ],
[ "key2", ["value2"] ],
];
However when I iterate the array to delete/set or change a key, the event doesn't run as expected:
For example:
console.log(keyVals);
function delKeyPair(key) {
for (var i = 0; i < keyVals.length; i++) {
if (keyVals[i][0] && keyVals[i][0] === key) {
Array.prototype.splice.call(keyVals, i, 1);
return true
}
}
return false
};
delKeyPair("key1");
console.log(keyVals);
When I first console.log() the array - it shows that "key1 has already been deleted, before the function is called.
here is a fiddle, not quite sure what's going on. Any help is much appreciated.
http://jsfiddle.net/3pfj8927/
key1 has not already been deleted before calling function:
try console.log(keyVals.length);
DEMO
Output:
Length before deleting: 2
Length after deleting: 1
The console runs asynchronously. It also keeps a reference to your object.
Your code is running just fine.
When you look at the object in the console, it shows you the current way it looks, not how it was at the time of the log.
If you replace console.log(keyVals); with console.log(keyVals.slice());, you should see the proper objects, because we copy them as-is.
The key1 has not been deleted. Note you're working on a reference of the given array. If you inspect the Array it will be loaded by the reference. Because you're changing the reference in the delKeyPair function it seems that there never was a key1.
If you copy the array on delete you'll see everything works like expected.

Javascript array becomes an object structure

I'm experiencing an odd behavior (maybe it isn't odd at all but just me not understanding why) with an javascript array containing some objects.
Since I'm no javascript pro, there might very well be clear explanation as to why this is happening, I just don't know it.
I have javascript that is running in a document. It makes an array of objects similar to this:
var myArray = [{"Id":"guid1","Name":"name1"},{"Id":"guid2","Name":"name2"},...];
If I print out this array at the place it was created like JSON.stringify(myArray), I get what I was expecting:
[{"Id":"guid1","Name":"name1"},{"Id":"guid2","Name":"name2"},...]
However, if I try to access this array from a child document to this document (a document in a window opened by the first document) the array isn't an array any more.
So doing JSON.stringify(parent.opener.myArray) in the child document will result in the following:
{"0":{"Id":"guid1","Name":"name1"},"1":{"Id":"guid2","Name":"name2"},...}
And this was not what I was expecting - I was expecting to get the same as I did in teh parent document.
Can anyone explain to me why this is happening and how to fix it so that the array is still an array when addressed from a child window/document?
PS. the objects aren't added to the array as stated above, they are added like this:
function objTemp()
{
this.Id = '';
this.Name = '';
};
var myArray = [];
var obj = new ObjTemp();
obj.Id = 'guid1';
obj.Name = 'name1';
myArray[myArray.length] = obj;
If that makes any difference.
Any help would be much appreciated, both for fixing my problem but also for better understanding what is going on :)
The very last line might be causing the problem, have you tried replacing myArray[myArray.length] = obj; with myArray.push(obj);? Could be that, since you're creating a new index explicitly, the Array is turned into an object... though I'm just guessing here. Could you add the code used by the child document that retrieves myArray ?
Edit
Ignore the above, since it won't make any difference. Though, without wanting to boast, I was thinking along the right lines. My idea was that, by only using proprietary array methods, the interpreter would see that as clues as to the type of myArray. The thing is: myArray is an array, as far as the parent document is concerned, but since you're passing the Array from one document to another, here's what happens:
An array is an object, complete with it's own prototype and methods. By passing it to another document, you're passing the entire Array object (value and prototype) as one object to the child document. In passing the variable between documents, you're effectively creating a copy of the variable (the only time JavaScript copies the values of a var). Since an array is an object, all of its properties (and prototype methods/properties) are copied to a 'nameless' instance of the Object object. Something along the lines of var copy = new Object(toCopy.constructor(toCopy.valueOf())); is happening... the easiest way around this, IMO, is to stringency the array withing the parent context, because there, the interpreter knows it's an array:
//parent document
function getTheArray(){ return JSON.stringify(myArray);}
//child document:
myArray = JSON.parse(parent.getTheArray());
In this example, the var is stringified in the context that still treats myArray as a true JavaScript array, so the resulting string will be what you'd expect. In passing the JSON encoded string from one document to another, it will remain unchanged and therefore the JSON.parse() will give you an exact copy of the myArray variable.
Note that this is just another wild stab in the dark, but I have given it a bit more thought, now. If I'm wrong about this, feel free to correct me... I'm always happy to learn. If this turns out to be true, let me know, too, as this will undoubtedly prove a pitfall for me sooner or later
Check out the end of this article http://www.karmagination.com/blog/2009/07/29/javascript-kung-fu-object-array-and-literals/ for an example of this behavior and explanation.
Basically it comes down to Array being a native type and each frame having its own set of natives and variables.
From the article:
// in parent window
var a = [];
var b = {};
//inside the iframe
console.log(parent.window.a); // returns array
console.log(parent.window.b); // returns object
alert(parent.window.a instanceof Array); // false
alert(parent.window.b instanceof Object); // false
alert(parent.window.a.constructor === Array); // false
alert(parent.window.b.constructor === Object); // false
Your call to JSON.stringify actually executes the following check (from the json.js source), which seems to be failing to specify it as an Array:
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
//stringify

Categories