deserialize JSON to JAVASCRIPT object [duplicate] - javascript

This question already has answers here:
Re-associating an object with its class after deserialization in Node.js
(4 answers)
Closed 6 years ago.
i have a question to deserialize JSON text to an javascript object, i test jquery and yui library, i have this class:
function Identifier(name, contextId) {
this.name = name;
this.contextId = contextId;
}
Identifier.prototype.setName = function(name) {
this.name = name;
}
Identifier.prototype.getName = function() {
return this.name;
}
Identifier.prototype.setContextId = function(contexId) {
this.contextId= contexId;
}
Identifier.prototype.getContextId = function() {
return this.contextId;
}
and i have this JSON:
{
"Identifier": {
"name":"uno",
"contextId":"dos"}
}
I want to the parse create an Identifier object, my problem is that this sentences:
var obj = jQuery.parseJSON('{"Identifier": { "name":"uno","contextId":"dos"}}');
or
var obj2 = JSON.parse('{"Identifier": { "name":"uno","contextId":"dos"}}');
Dont work, the var obj and obj2 aren't an Identifier object, how can i parse this?
Thanks
This question is not the duplicate, because it was made 5 years before than the question that Michael marks as duplicated

You could create a function that initializes those objects for you. Here's one I quickly drafted:
function parseJSONToObject(str) {
var json = JSON.parse(str);
var name = null;
for(var i in json) { //Get the first property to act as name
name = i;
break;
}
if (name == null)
return null;
var obj = new window[name]();
for(var i in json[name])
obj[i] = json[name][i];
return obj;
}
This creates an object of the type represented by the name of the first attribute, and assigns it's values according to the attributes of the object of the first attribute. You could use it like that:
var identifier = parseJSONToObject('{"Identifier": { "name":"uno","contextId":"dos"}}');
console.log(identifier);
Live example

Related

Get key from value in Json [duplicate]

This question already has answers here:
Javascript get Object property Name
(4 answers)
Closed 7 years ago.
I have a Json object in following format
MyJsonObject= {
'Animal': ['Lion', 'Tiger', 'Elephant'],
'Human': ['Man', 'Woman']
};
I want to get the key as return type if we pass value to function. Eg If I pass value =Man, function should return Human as return type. similarly, If I passed Tiger as value than I want to get Animal as return value.
Any help will be appreciated
Hi the snippet bellow should work.
You can try here http://jsfiddle.net/xtdqodzk/1/
MyJsonObject= {
'Animal': ['Lion', 'Tiger', 'Elephant'],
'Human': ['Man', 'Woman']
};
function find(value){
for(var prop in MyJsonObject ){
if(MyJsonObject.hasOwnProperty(prop)){
for(var i =0 ;i<MyJsonObject[prop].length;i++){
if(MyJsonObject[prop][i] === value){
return prop;
}
}
}
}
}
alert(find('Man'));
You can try to modify Object prototype
Object.prototype.findKey = function(value) {
for (var key in this) {
if (this.hasOwnProperty(key)) {
for (var i = 0; i < this[key].length; i++) {
if (this[key][i] === value) {
return key;
}
}
}
}
}
var MyJsonObject = {
'Animal': ['Lion', 'Tiger', 'Elephant'],
'Human': ['Man', 'Woman']
};
console.log(MyJsonObject.findKey('Man'));
The advantage of doing this way is if you have another json object you can call .findKey function on that object as well since all objects inherit functions and properties from Object.prototype object (prototypal inheritance).

dynamic setting values in javascript object(json) [duplicate]

This question already has answers here:
How to set object property (of object property of..) given its string name in JavaScript?
(16 answers)
Closed 8 years ago.
I've read this existing question on stackoverflow.
My target is to set a property on a "nested Property and set a new Value (without eval!):
What i have is a dynamic string as example : “A.B.C”
And a JSON Object:
var obj ={
A: {
B: {
C: 23
C1: {}
}
}
}
Now i want to access this property and set it:
If the string has a fixed amount of properties i can just write:
obj[prop1][prop2][prop3] = 42
What would be the way to make this dynamic, so when passing “A.B” the object at B is replaced?
Something like this will work..
var str = "A.B.C";
var obj ={
A: {
B: {
C: 23,
C1: {}
}
}
};
updateObj(obj,str,10);
function updateObj(obj,str,val){
var tok = str.split(".");
var update = function(obj, index){
if (index < tok.length){
if ( !obj.hasOwnProperty(tok[index])){
obj[tok[index]] = {};
}
if (index == tok.length-1){
obj[tok[index]] = val;
}
update(obj[tok[index]],++index);
}
}
update(obj,0);
}
console.log(obj);

Creating object with dynamic keys [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 8 years ago.
First off, I'm using Cheerio for some DOM access and parsing with Node.js. Good times.
Heres the situation:
I have a function that I need to create an object. That object uses variables for both its keys and values, and then return that single object. Example:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value');
return { key : value }
})
callback(null, inputs);
}
It outputs this:
[ { key: '1' }, { key: '1' } ]
(.map() returns an array of objects fyi)
I need key to actually be the string from this.attr('name').
Whats the best way to assign a string as a key in Javascript, considering what I'm trying to do?
In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.
The syntax is:
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity.
Using Babel or Google's traceur, it is possible to use this syntax today.
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.
To use a "dynamic" key, you have to use bracket notation:
var obj = {};
obj[myKey] = value;
In your case:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}
You can't define an object literal with a dynamic key. Do this :
var o = {};
o[key] = value;
return o;
There's no shortcut (edit: there's one now, with ES6, see the other answer).

Set an object property by using its value [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Variable as the property name in a JavaScript object literal? [duplicate]
(3 answers)
Closed 8 years ago.
Say I call following function:
var query = makeQuery("email", "foo#bar.com");
The implementation I have is:
makeQuery = function (key, value) {
return { key: value};
}
The object I end up with is: {"key": "foo#bar.com"}, which is obviously wrong. I would like to obtain {"email": "foo#bar.com"} instead. I tried setting it like so:
makeQuery = function (key, value) {
return { JSON.stringify(key): value};
}
... but I get a "SyntaxError: Unexpected token ." I've also thought of using toString() and even eval(), without success. So my problem is to be able to set the property of the object returned in makeQuery() using its real value, that is, pick up the value of 'key', not setting the property with the 'key' literal.
Thanks for the help.
Create the object first and then use the square bracket syntax so you can set the property using the value of key:
makeQuery = function (key, value) {
var query = {};
query[key] = value;
return query;
};
For variable keys in objects, use
var obj[key] = value
So then it becomes:
function makeQuery(key, value) {
var obj = {};
obj[key] = value;
return obj;
}
define an object..
makeQuery = function (key, value) {
var o = {};
o[key] = value;
return o;
}

set an object property with sugar like obj['level1.level2.leve3'] = value [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get element on any level of an object in Javasscript
Good day for every one!
I'am really confused with this one:
I have an Object:
var someObject = {}
So, next I wanna set properties like this:
someObject['errors.email'] = value1;
someObject['errors.password'] = value2;
and after have an object:
{
errors: {
email: 'some value 1'
,password: 'some value 2'
}
}
is it possible with some syntactic sugar?
The most sweet issue is
function setValueByPath(obj, path, value) {
var pathArray = path.split('.');
var pointer = obj;
var i = 0, l = pathArray.length-1, prop;
for (; i<l; i++) {
prop = pathArray[i];
pointer = pointer.hasOwnProperty(prop) ? pointer[prop] : (pointer[prop] = {});
}
pointer[pathArray[i]] = value;
}
thanks to Roman Ziva for advice (see here http://jsperf.com/autocreate-obj)
an example see here http://jsfiddle.net/zafod/KxesD/
You can set the properties like this,
var errors = someObject['errors'] = {};
errors['email'] = value1;
errors['password'] = value2;
Else,
someObject['errors'] = { "email": value1, "validation": {"fatal": {"email": value2}}}
There is no other best option for this.

Categories