how to get the content of java script object in another object? - javascript

how to get the content of java script object in another object ?
let say my variable are like follows :
var credentials ={
"name":userName,
"passwd":password
}
var params={
"Credentials":credentials
}
am passing params as an parameter to same other function.In that function i have another object pkt ,as follows :
var pkt={
"name":xxx,
//XXXX
}
what to code at XXXX so that my final pkt structure should be like:
pkt={
"name":xxx,
"Credentials": {
"name":userName,
"passwd":password
}
}
we may have multiple objects inside params,the requirement is that the key value pair should come accordingly.
the equivalent java code is as follows:
Iterator iterKeys = params.keySet().iterator();
while (iterKeys.hasNext())
{
String key = (String)iterKeys.next();
JSONValue value = params.get(key);
pkt.put(key, value);
}
Thanks.

Javascript objects are just Hashmaps.
var credentials = {
"name": "userName",
"passwd": "password"
}
var params = {
"Credentials": credentials
}
var pkt = {
"name": "xxx",
}
for (var property in params) {
if (params.hasOwnProperty(property)) {
var value = property;
pkt[property] = params[property];
}
}
alert(JSON.stringify(pkt));
You can just assign as seen in [this fiddle]
(http://jsfiddle.net/TfWMy/)

You could use a library function like $.extend or _.extend:
pkt = $.extend(pkt, params);
Otherwise you can loop through params and add each key/value pair to pkt:
for (var key in params){
pkt[key] = params[key];
}
Use hasOwnProperty to avoid looping over ancestor members.

You can also use associative array structure.
i.e
var credentials = {
"name": "userName",
"passwd": "password"
}
var pkt = {
"name": "xxx",
}
pkt["Credentials"] = credentials
Not particularly sure about this, but this should work as expected.

Here's two quick functions that should do what you're looking for. The first adds the keys and values to a new object, the second function adds the keys and values to the first object.
var mergeObjectsToNew = function(o1, o2) {
var r = {};
for (var key in o1) {
r[key] = o1[key];
}
for (var key in o2) {
r[key] = o2[key];
}
return r;
}
var mergeObjects = function(o1, o2) {
for (var key in o2) {
o1[key] = o2[key];
}
return o1;
}

I think you are looking to extend your object with another.
Please follow the code and I hope this is the thing you are require.
var credentials ={
"name":"",
"passwd":""
}
var params={
"Credentials":credentials
}
var pkt={
name:"ABC"
};
function Extends(param1,param2){
var object = $.extend({}, param1, param2);
console.log(object);
}
Extends(params,pkt);
Please find Fiddle Below
Fiddle

Related

Deserialize JSON into specific/existing JavaScript object

Is there a way to parse a JSON string into an existing Javascript object:
Lets say i have created this object:
var ClientState = function(){
this.userId ="";
this.telephoneState = "UNKNOWN";
this.agentState = "UNKNOWN";
this.muteState = "UNKNOWN";
this.number = "";
this.ready = false;
}
ClientState.prototype = {
doNastyStuff: function(){
//do something here
}
//other methods here
}
I have this json coming through the wire:
{"userId":"xyz","telephoneState":"READY","agentState":"UNKNOWN","muteState":"MUTED","number":"","ready":false}
Is it possible to deserialize into the object specified above? So that i can use all methods specified on it?
Or in general is it possible to deserialize into a specific target object (without specifying deserialization in this target object)?
(I know that i could create an constructor that accepts json or a parsed object.)
Yes! You can use Object.assign to overwrite the attributes of an object with another object:
var ClientState = function() {
this.userId = "";
this.telephoneState = "UNKNOWN";
this.agentState = "UNKNOWN";
this.muteState = "UNKNOWN";
this.number = "";
this.ready = false;
}
var c = new ClientState();
console.log('prior assignment: ', c);
Object.assign(c, {
"userId": "xyz",
"telephoneState": "READY",
"agentState": "UNKNOWN",
"muteState": "MUTED",
"number": "",
"ready": false
});
console.log('after assignment: ', c);
Note that it will overwrite all the properties of source object (first object) with the target object (second object) by matching the respective keys. The keys, which are non-existing in the target object are left intact in the source object.
Is this what you had in mind?
function parseAs(targetClass, rawJSON) {
return Object.assign(new targetClass(), JSON.parse(rawJSON));
}
var clientState = parseAs(ClientState, '{"userId":"xyz"}');
I don't think there's a native JSON method that does this, but you can just write a function like the one above. You can even define it on the JSON class itself:
JSON.parseAs = function(targetClass, rawJSON) {
return Object.assign(new targetClass(), JSON.parse(rawJSON));
}
If you want to use your function to add the object values to the instance properties:
function ClientState() {
this.userId = "";
this.telephoneState = "UNKNOWN";
this.agentState = "UNKNOWN";
this.muteState = "UNKNOWN";
this.number = "";
this.ready = false;
}
ClientState.prototype = {
doNastyStuff: function(json) {
const data = JSON.parse(json);
Object.assign(this, data);
}
}
const json = '{"userId":"xyz","telephoneState":"READY","agentState":"UNKNOWN","muteState":"MUTED","number":"","ready":false}';
const clientState = new ClientState();
clientState.doNastyStuff(json);
console.log(clientState);

Access dynamically created objects in Javascript

I am attempting to dynamically create an object with name-value pairs using html input fields. This is what i have so far:
var taskComplete = {
newTask: function(arg) {
var fieldObj = {},
selector = arg,
inputFields = document.getElementsByClassName(selector);
for (var i=0;i<inputFields.length;i++) {
var attrValue = inputFields[i].getAttribute("name"),
value = inputFields[i].value,
newFieldObj = fieldObj[i] = {[attrValue]: value };
console.log(newFieldObj);
}
}
}
taskComplete.newTask('input');
The console log outputs:
Object {title: ""}
Object {description: ""}
Object {date: ""}
Question1:
How do i access these objects? they all share the same name eg. 'Object' so 'object.title' does not work.
Question2:
Is there a way to combine these objects into a single object?
eg.
var obj = {
title: "",
description: "",
date: "",
}
code example with html: codepen.io
Hope this make sense. Thank you for any and all assistance.
I will answer your questions in the reverse order, makes more sense, you will see.
Question2: Is there a way to combine these objects into a single object?
Yes, I am happy to inform you that you absolutely can. Where you do
newFieldObj = fieldObj[i] = {[attrValue]: value };
simply do
fieldObj[attrValue] = value;
What this does, is the following: On the fieldObj, which is a plain {} set a key named after the value of attrValue and pair that key with the value value
Question1: How do i access these objects? they all share the same name eg. 'Object' so 'object.title' does not work.
In order to be able to access these objects, your newTask method should be returning them. So, at the end of your newTask method, simply do return fieldObj; like so
var taskComplete = {
newTask: function(arg) {
var fieldObj = {},
selector = arg,
inputFields = document.getElementsByClassName(selector),
attrValue,
value;
for (var i=0;i<inputFields.length;i++) {
attrValue = inputFields[i].getAttribute("name");
value = inputFields[i].value;
fieldObj[attrValue] = value;
}
return fieldObj;
}
}
and then store the returned value to a new variable like so:
var aFancyName = taskComplete.newTask('input');
Here's the modified pen: http://codepen.io/anon/pen/XdjKQJ
Not super clear on what you are trying to do here.
Instead of creating a new object for each iteration of your loop, why not just assign those properties to the fieldObj you already have?
Then you can just return that object and do whatever you want with it in the calling code:
'use strict';
// ** TASK OBJECT ** //
var taskComplete = {
newTask: function(selector) {
var fieldObj = {},
inputFields = document.getElementsByClassName(selector);
for (var i = 0; i < inputFields.length; i++) {
var attrKey = inputFields[i].getAttribute("name"),
value = inputFields[i].value;
fieldObj[attrKey] = value;
}
return fieldObj;
}
}
var o = taskComplete.newTask('input');
console.dir(o);
http://codepen.io/anon/pen/reMLPB?editors=0010

NOT using reference to object (javascript)

The below :-
req.session.user = doc[0];
req.session.user.password = null;
Makes doc[0].password = null!
What do i do to prevent that?
Edit: Where doc[0] = { name: 'sangram', e-mail: 'abc.in', password : 'pwd' }
The only way to do so is to copy every property of an object:
req.session.user = {};
for (var key in user) {
if (key !== 'password') req.session.user[key] = user[key];
}
If user is a mongoose document, you probably should convert it to plain object first:
req.session.user = {};
var json = user.toObject();
for (var key in json) {
if (key !== 'password') req.session.user[key] = json[key];
}
But the easiest way to do what you want is to adopt some helpful library like underscore or lodash:
req.session.user = _.omit(user.toObject(), 'password');
For simple case of simple objects, I wrote a small helper function:
function ShallowClone(obj) {
var clone = {};
for (var key in obj)
clone[key] = obj[key];
return clone;
}
Usage in your case:
req.session.user = ShallowClone(doc[0]);
req.session.user.password = null; //won't affect doc[0] password
Live test case. (with dummy object)
I would recommend updating or changing your question in the future.
What is the most efficient way to deep clone an object in JavaScript?
How do I correctly clone a JavaScript object?
Crockford provides a very good answer here
You can't prevent this. The user property is set to that object doc[0]. Later you edit .password property of that newly assigned object. If you want to keep the password separately you have to assign doc[0] to another object.
req.session.user = {};
req.session.user.doc = doc[0];
req.session.user.password = null;
Here is a method for cloning/extending an object:
var extend = function() {
var process = function(destination, source) {
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
destination[key] = source[key];
}
}
return destination;
};
var result = arguments[0];
for(var i=1; i<arguments.length; i++) {
result = process(result, arguments[i]);
}
return result;
};
And its usage:
var original = { value: "bla" };
var duplication = extend({}, original, { newProp: "test"});

Creating a .net like dictionary object in Javascript

I want to create a object in JavaScript which will store values in key, value pair and I should be able to pass some key and should be able to get its value back. In .NET world we can use dictionary class for this kind of implementation. Do we have any option in JavaScript world? I am using ExtJs 4.1, so if you know of any option in ExtJS even that would work.
I have tried something like this but I cannot get value by key.
var Widget = function(k, v) {
this.key = k;
this.value = v;
};
var widgets = [
new Widget(35, 312),
new Widget(52, 32)
];
Just use a standard javascript object:
var dictionary = {};//create new object
dictionary["key1"] = value1;//set key1
var key1 = dictionary["key1"];//get key1
NOTE: You can also get/set any "keys" you create using dot notation (i.e. dictionary.key1)
You could take that further if you wanted specific functions for it...
function Dictionary(){
var dictionary = {};
this.setData = function(key, val) { dictionary[key] = val; }
this.getData = function(key) { return dictionary[key]; }
}
var dictionary = new Dictionary();
dictionary.setData("key1", "value1");
var key1 = dictionary.getData("key1");
How about this class taken from Marijn Havereke's book Eloquent JavaScript
The fiddle
function Dictionary(values) {
this.values = values || {};
var forEachIn = function (object, action) {
for (var property in object) {
if (Object.prototype.hasOwnProperty.call(object, property))
action(property, object[property]);
}
};
Dictionary.prototype.containsKey = function(key) {
return Object.prototype.hasOwnProperty.call(this.values, key) &&
Object.prototype.propertyIsEnumerable.call(this.values, key);
};
Dictionary.prototype.forEach = function(action) {
forEachIn(this.values, action);
};
Dictionary.prototype.lookup = function(key) {
return this.values[key];
};
Dictionary.prototype.add = function(key, value) {
this.values[key] = value;
};
};
var numberDic = new Dictionary({One: 1,Two: 2, Three: 3});
//-- does key exist
console.log(numberDic.containsKey("One"));
console.log(numberDic.containsKey("One"));
console.log(numberDic.containsKey("Four"));
//-- loop through each item in the dic
numberDic.forEach(function(key, value) {
console.log(key, "is", value);
});
//-- works with complex objects
//------------------------------------------
var complexObjectDic = new Dictionary({
Microsoft: {
Something: "Real Interesting",
About: "Microsoft",
Will: "Go",
Here: ".",
ProductPrices: {
WindowsPhone: 55.88,
Windows :{
WinXp : 180.00,
Win7 : 200.00,
Win8 : 150.00
}
}
},
Apple: {
Did: "you",
Hear: "the",
New: "iphone",
Will: "be coming out soon",
}});
//-- does key exist
console.log(complexObjectDic.containsKey("Microsoft"));
console.log(complexObjectDic.containsKey("Apple"));
console.log(complexObjectDic.containsKey("Facebook"));
//-- search the dic by key
console.log(complexObjectDic.lookup("Microsoft"));
console.log(complexObjectDic.lookup("Apple"));
//-- add item to dic
complexObjectDic.add("Instagram", {
This: "is",
Another: "object",
That: "I willl be Adding"
});
//-- loop through each item in the dic
complexObjectDic.forEach(function(key, value) {
console.log(key, value);
});
var widget={};
var key='k';
widget[key]='v';
alert(widget.k);//gives you v

Can you use custom objects as properties of an object in javascript?

Suppose I create a custom object/javascript "class" (airquotes) as follows:
// Constructor
function CustomObject(stringParam) {
var privateProperty = stringParam;
// Accessor
this.privilegedGetMethod = function() {
return privateProperty;
}
// Mutator
this.privilegedSetMethod = function(newStringParam) {
privateProperty = newStringParam;
}
}
Then I want to make a list of those custom objects where I can easily add or remove things from that list. I decide to use objects as a way to store the list of custom objects, so I can add custom objects to the list with
var customObjectInstance1 = new CustomObject('someString');
var customObjectInstance2 = new CustomObject('someOtherString');
var customObjectInstance3 = new CustomObject('yetAnotherString');
myListOfCustomObjects[customObjectInstance1] = true;
myListOfCustomObjects[customObjectInstance2] = true;
myListOfCustomObjects[customObjectInstance3] = true;
and remove custom objects from the list with
delete myListOfCustomObjects[customObjectInstance1];
but if i try to iterate through the list with
for (i in myListOfCustomObjects) {
alert(i.privilegedGetMethod());
}
I would get an error in the FireBug console that says "i.privilegedGetMethod() is not a function". Is there a way to fix this problem or an idiom in javascript to do what I want? Sorry if this is a dumb question, but I'm new to javascript and have scoured the internet for solutions to my problem with no avail. Any help would be appreciated!
P.S. I realize that my example is super simplified, and I can just make the privateProperty public using this.property or something, but then i would still get undefined in the alert, and I would like to keep it encapsulated.
i won't be the original object as you were expecting:
for (i in myListOfCustomObjects) {
alert(typeof i); // "string"
}
This is because all keys in JavaScript are Strings. Any attempt to use another type as a key will first be serialized by toString().
If the result of toString() isn't somehow unique for each instance, they will all be the same key:
function MyClass() { }
var obj = {};
var k1 = new MyClass();
var k2 = new MyClass();
obj[k1] = {};
obj[k2] = {};
// only 1 "[object Object]" key was created, not 2 object keys
for (var key in obj) {
alert(key);
}
To make them unique, define a custom toString:
function CustomObject(stringParam) {
/* snip */
this.toString = function () {
return 'CustomObject ' + stringParam;
};
}
var obj = {};
var k1 = new CustomObject('key1');
var k2 = new CustomObject('key2');
obj[k1] = {};
obj[k2] = {};
// "CustomObject key1" then "CustomObject key2"
for (var key in obj) {
alert(key);
}
[Edit]
With a custom toString, you can set the object as the serialized key and the value to keep them organized and still continue to access them:
var customObjectInstance1 = new CustomObject('someString');
var customObjectInstance2 = new CustomObject('someOtherString');
var customObjectInstance3 = new CustomObject('yetAnotherString');
myListOfCustomObjects[customObjectInstance1] = customObjectInstance1;
myListOfCustomObjects[customObjectInstance2] = customObjectInstance2;
myListOfCustomObjects[customObjectInstance3] = customObjectInstance3;
for (i in myListOfCustomObjects) {
alert(myListOfCustomObjects[i].privilegedGetMethod());
}
The for iteration variable is just the index, not the object itself. So use:
for (i in myListOfCustomObjects) {
alert(myListOfCustomObjects[i].privilegedGetMethod());
}
and, in my opinion, if you use an Object as an array index / hash, it just would be converted to the string "Object", which ends up in a list with a single entry, because all the keys are the same ("Object").
myListOfCustomObjects =[
new CustomObject('someString'),
new CustomObject('someOtherString'),
new CustomObject('yetAnotherString')
]
you will get access to any element by index of array.

Categories

Resources