How to add new attribute to JSON object using JavaScript? - javascript

How do I add new attribute to JSON object using JavaScript?
I want to add a new attribute to JSON object.

JSON stands for JavaScript Object Notation. A JSON object is really a string that has yet to be turned into the object it represents.
To add a property to an existing object in JS you could do the following.
object["property"] = value;
or
object.property = value;
If you provide some extra info like exactly what you need to do in context you might get a more tailored answer.

Related

Can a DOM element attribute value be a JavaScript object?

Maybe this is a duplicate, but I could find the similar question.
For example we have <input data-student=""> and we have a var studentObj = {...}. Can I assign studentObj to input data-student attribute? Will it contradict the standards?
Attribute values are always strings, so no. You have several options:
Store the object in string form, such as JSON, in the attribute.
Store the object in a container somewhere and keep a key for it in the attribute.
If you mean on an element instance, it's possible to add your own properties to element instances, and those properties can have any value (search for "expando properties" for details), but be sure to use a name that will be really, really specific to your situation. (jQuery does this, for example, for the data it manages via the data function.)
And in fact, if you're using jQuery, you could use data to store the object, leaving the details to jQuery. :-)
Sure will! HTML doesn't accept a data type of object, it is in fact just plain text
What you are looking for is the dataset attribute. But it only stores strings, you can solve this with JSON.
el.dataset.student = JSON.stringify(studentObj);
studentObj = JSON.parse(el.dataset.student);
With jquery's data method (https://api.jquery.com/data/) you can store objects without any further problems.
Read more:
Dataset: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset -
JSON: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
Actually your desire doesn't contradict the standards, you must stringify your object and put in your data attribute then in usage parse it, like below:
const q = document.querySelector.bind(document); // it's just for easiness
const input = q('input'); //select the input
const studentObj = { // make your student object
something: 'some-value'
};
input.dataset.student = JSON.stringify(studentObj);
// put the student object in your selected input data attribute
When you wanna use it you can parse it:
const input = q('input'); //select the input
const myDesireObject = JSON.parse(input.dataset.student);

How do I access the 'str' value in my object?

I am trying to return the value under the key 'str' in an Object but I am having trouble accessing the value.
This is what is returned in the console:
Currently I am using a map function to go over the array and just return the _str value like so:
let idx = currentArray.map(function(x) {
return x._id._str;
});
However it is still returning the value as an object. How can I get just the value of the _str key?
Here is the full array without specifying the id field. This is what is returned if you jsut return 'x' in the map function.
You've clarified that the screenshot is of x._id. So to access _str, you'd use x._id[0]._str: The _str property is in the object referenced by the 0 property (the first entry in the array x._id refers to).
Note that in general, _-prefixed properties are meant not to be accessed by code outside the code responsible for the objects in question. You don't seem to be responsible for them, so accessing those properties is likely to make your code rely on undocumented properties that may change in the next "dot" release of whatever lib you're using. It's just convention, but it's a very common convention.
If you right click on the property, most browser consoles offer the ability to copy property path.
Based on this SO post and the docs, it appears that you can probably use x._id.str.
If I understand correctly, you are receiving the str value but it is an object instead of the string literal. In other words, you are getting _str: "598..." instead of "598....". A possible solution would be to use the mongo javascript function to convert the str value to a string.
In your case, I think something like return x._id.str; may work as _id is a MongoID.ObjectID.
I've also linked the documentation below for reference.
https://docs.mongodb.com/manual/reference/method/ObjectId/
Here's a relevant SO answer as well: Convert ObjectID (Mongodb) to String in JavaScript
I think you should write x[_id]._str because _id is one of the array objects.

What is the Type of a javascript object property?

Javascript objects use a key value system (like a hash, map, or dictionary in other programming languages). The key is referred to as a property and within an object is written like this:
var object = { property01: value01, property02: value02 }
Within objects we can access the value of the property using two access methods.
object.property01
object['property01']
In the example above property01 and property02:
What is the type of the variable holding the property name, and how is it stored in memory?
I'm not sure if I understand your question correctly, but the closest answer I could reference is this:
Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
It's a variable, but instead of being attached to the window object, it's attached to another variable.

Saving an element as a index in a object

I'd like to save a DOM element in a object. But not as a value, i want save it as a key of the object. But i think the core of javascript is not able to do that.
data={}
data[$('div#a')] = 'A';
data[$('div#b')] = 'B';
console.log(data[$('div#a')]); //return B
Do you know some way to save the element in a index object?
Imagine i have XXXXXX elements on my document. If i want to access to the element properties when some event happen on it i dont want to iterate XXXXXX elements to find it.
Why i don't use data of jquery for two reasons:
I want to do it on native javascript
I dont want another array to iterate separate data from the elementid
So the perfect way to do it was have only one object with the elements on the key to acces them easy. And if i want iterate them i only have to do for i in data
JavaScript objects will only accept strings as keys, and JS will use .toString() if you try to use anything else as a key, typically resulting in everything being stored under the (single) key "[object Object]".
Is there any reason you can't use $('#a').data() to store the data associated with that element directly on the element?
Failing that, assuming that every such element has an ID, just use the element ID as the object key.
NB: ES6 has a Map object which can use arbitrary keys, but that's only an experimental feature in current browsers. However even then you would have to use the actual element as the key rather than a jQuery wrapped $(element) object, since $('#a') !== $('#a') - you would have to use the exact same original jQuery object each time you access the map, not a newly constructed object.
Javascript objects only accept string as key.
So if you try to give key value other than string, javascript will internally call .toString() method of that object and use return value of it as key.
Object keys have to be stings.
You can use the data method to associate anything to the element:
$('div#a').data('name', 'A');
$('div#b').data('name', 'B');
console.log($('div#a').data('name')); //return B

Custom JavaScriptConverter Classes

Does anyone know of decent examples of custom JavaScriptConverter classes? The MSDN's only example is of one converting a ListItemCollection. What about custom classes? What if the custom class has a property of another custom class? Do we need two converters? Any references would be greatly appreciated.
Thanks!
You should only need one converter. The example basically outlines how to use the JavaScript converter for any custom class. It doesn't need to be a class that is part of the framework.
It will also work for any properties of a custom class that are themselves a custom class.
JSON views objects as collections of key/value pairs, so the documentation example shows how you should take any properties of your object and put them into Dictionaries (a type of Key/Value pair object). If you need a nested custom type, you can just nest Key/Value pairs inside of your main Key/Value pair collection.
Also, unless you have very specific needs (built-in serialization either won't work, or doesn't output what you want), you should just use the JavaScriptSerializer class.
JavaScriptSerializer serializer = new JavaScriptSerializer();
MyCustomObject obj = new MyCustomObject();
string json = serializer.Serialize(obj);
MyCustomObject object2 = serializer.Deserialize<MyCustomObject>(json);
That should do what you want in 95% of cases.

Categories