Add Jquery object as key to another object - javascript

Can I add Jquery Object to the blank object as key. For example:-
var obj = {};//blank object
var myId = $("#myId");//jQuery Object
var myId2 = $("#myId2");//another jQuery Object
obj[myId] = "Trying to add myId as a key";
obj[myId2] = "Trying to add myId2 as a key";
But the output of the obj contains only one key. Is the above thing is possible in JS or not?
Thanks in advance.

You have to use a string as property name (e.g. the id of the jquery object?).
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

If you want to keep the reference to object you can use an array of objects instead of an object:
[
{
"jQueryElement": myId1,
"note": "Trying to add myId as a key"
},
{
"jQueryElement": myId2,
"note": "Trying to add myId2 as a key"
}
]
Then you will be able to do:
function getNoteOfJqueryObj(element) {
element = $(element);
for (var i in array) {
if (array[i].jQueryElement[0] == element[0]) {
return array[i].note;
}
}
return undefined;
}
I guess that this is one of the best ways you can choose.
JSFIDDLE

Related

Javascript how to properly clone and not modify an object [duplicate]

This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 6 years ago.
I have an object, which i search the keys and modify the values if a key match is found:
var myData = // some http.get which returns a JSON object.
Imagine myData is:
myData : {
"suffix" : "mr",
"fname" : "jullian",
"lname" : "exor",
"dobGmt" : 145754294700000
"addressLine1" : "xxx",
"street" : "xxx",
"rentStartedGmt" : 145754294700000,
"deposit" : "50.00",
"occupation" : "math teacher",
"profession" : {
"careerStartedGmt": 1458755224800000,
"careerEndGmt": 1459854224800000,
}
}
$scope.viewData = function() {
var objClone = _.clone(myData);
objClone = myFactory.ProcessData(objClone);
$scope.view = objClone;
};
$scope.viewProducts = function() {
};
MyFactory:
myModule.factory('myFactory', function() {
return {
ProcessData: function(data) {
var tmp = data;
function findGmt(tmp) {
for (var key in tmp) {
var v = tmp[key];
if (key.indexOf("Gmt") !== -1) {
tmp[key] = tmp[key].format('DD-MM-YY HH:mm');
}
}
}
findGmt(tmp);
return tmp;
}
}
});
User can click on viewData button which calls $scope.viewData which displays the formatted JSON in a modal on the same page.
User then clicks on viewProducts which calls $scope.viewProducts which displays a list of products in a modal on the same page.
However, after clicking viewProducts, if i go back to click viewData again, on debugging, i can see var objClone is already formatted, rather than taking a new clone of _.clone(myData);
Have a missed how to clone/not modifiy original objects?
Usually, clone functions (that can now be replaced by the standard Object.assign) only copy the provided object properties into a new object. They do not recursively clone the values of the object. That means that the content of your profession property, for example, is the same object for the cloned and the original: myData.profession === objClone.profession is true.
What you are looking for is a deep clone function.
You have to use var copiedObj = angular.copy(myObj). It will create copy of the myObj but changing myObj won't change anything in copiedObj.

How would I go about using a multidimensional array variable in javascript

Hi there before I start I did try looking through the search about writing variables so if this has been asked and answered then I do apologise but this is baffling me ....
So here goes ..
example of what I am talking about
var i = e[ab]
var n = e[cd][ef]
var t = e[cd][gh]
I know that when I want var i I can put e.ab but how would I go about writing var n and var t
So assuming your object looks like this (based on your description, it sounds like you want to access an object which is the property of another object), and you want to access them through the indexer properties (which would be a property of a property).
var e = {
ab : "variableOne",
cd : {ef:"ef object"},
gh : {ij:"ij object"},
}
var i = e["ab"]
//if these are properties, then you need to add quotes around them
//to access a property through the indexer, you need a string.
var n = e["cd"]["ef"]
var t = e["gh"]["ij"]
console.log(i);
console.log(n);
console.log(t);
console.log("this does the same thing:")
console.log(e.ab);
console.log(e.cd.ef);
console.log(e.gh.if);
In your example the object would look like
//e is the parameter, but I show it as a variable to show
// it's relation to the object in this example.
e = {
now_playing: {artist:"Bob Seger"; track:"Turn the Page"}}
}
this is different than an array of arrays:
var arr = [
['foo','charlie'],
['yip', 'steve'],
['what', 'bob', 'jane'],
];
console.log(arr[0][0]); //foo
console.log(arr[0][1]); //charlie
console.log(arr[1][0]); //yip
console.log(arr[1][1]); //steve
console.log(arr[2][2]); //jane
https://jsfiddle.net/joo9wfxt/2/
EDIT:
Based on the JSON provided, it looks like parameter e in the function is assigned the value of the item in the array. With your code:
this line will display: "Rock you like a hurricane - Nontas Tzivenis"
$(".song_title .current_show span").html(e.title);
and this line will display: "Rascal Flatts - Life is a Highway".
$(".song_title .current_song span").html(e.np);
If it's not displaying you might want to double check your JQuery selectors. This ".song_title .current_song span" is selecting it by the classes on the element.
I think you are in need of a bit of a refresher on basic JavaScript syntax. Here's how you can assign an "empty object" to a variable, then start to assign values to it's properties:
e = {}
e.ab = {}
e.cd = {}
e.cd.ef = "data"
or you can use the associative array syntax for property access:
e = {}
e["ab"] = {}
e["cd"] = {}
e["cd"]["ef"] = "data"
You see the latter is using the object e like a two-deep associative array. Is that what you are looking to do?
JavaScript is not strongly typed. So an Array "a" could contain objects of different types inside.
var a = [ "a value", [1, 2, 3], function(){ return 5 + 2;}];
var result = a[0]; //get the first item in my array: "a value"
var resultOfIndexedProperty = a[1][0]; //Get the first item of the second item: 1
var resultOfFunc = a[2](); //store the result of the function that is the third item of my array: 7
Hope this helps a little.

Adding a new array element to a JSON object

I have a JSON format object I read from a JSON file that I have in a variable called teamJSON, that looks like this:
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}
I want to add a new item to the array, such as
{"teamId":"4","status":"pending"}
to end up with
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}
before writing back to the file. What is a good way to add to the new element? I got close but all the double quotes were escaped. I have looked for a good answer on SO but none quite cover this case. Any help is appreciated.
JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON
var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
First we need to parse the JSON object and then we can add an item.
var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);
Finally we JSON.stringify the obj back to JSON
In my case, my JSON object didn't have any existing Array in it, so I had to create array element first and then had to push the element.
elementToPush = [1, 2, 3]
if (!obj.arr) this.$set(obj, "arr", [])
obj.arr.push(elementToPush)
(This answer may not be relevant to this particular question, but may help
someone else)
Use spread operator
array1 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Organization"
}
];
array2 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Division"
}
];
array3 = [
{
"column": "Level",
"operator": "=",
"value": "Country"
}
];
console.log(array1.push(...array2,...array3));
For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.
'<i class="fa fa-shopping-cart"></i>Add to cart'
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('<i class="fa fa-check"></i>Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
});
Storage.prototype.setObj = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObj = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
After adding JSON object to Array result is (in LocalStorage):
[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]
after this action you can easily send data to server as List in Java
Full code example is here
How do I store a simple cart using localStorage?

Dynamic name in json key

I'm trying to make a JSON dynamically but when I do something like this:
var jsonVar = {
"section": {}
}
var elementsStoragePrefix = "_app_",
elementName = elementsStoragePrefix + "some_name";
$.extend(jsonVar .section, { elementName: "<option>This is a text</option>"});
I got the key as elementName and not _app_some_name
jsonVar.section =>
Object
elementName: "<option>This is a text</option>"
__proto__: Object
When creating object literals, you don't need to quote the property names, so in your example elementName will be taken literally. Thankfully, you can use the square-bracket-syntax (or however you spell that):
var extendObject = {};
extendObject[elementName] = '<option>Foobar</option>';
$.extend(jsonVal.section, extendObject);
//or, to use brackets all the way:
$.extend(jsonVal['section'], extendObject);
That should fix things for you
jsonVar.section[elementName] = "<option>This is a text</option>";

any danger in using an html object as attribute "name" in javascript object?

in linking javascript objects with html objects
// javascript element
var element = { tag:'input', name: 'email', value:null, dom: null,
verifyFunc: function() {...}, postFunc: function() {...},
rcdElement: some_element }
// lookup javascript element from dom
var doms = {};
// create html element for dom
var item = document.createElement(element.tag);
item.name = element.name;
...
// cross-link
doms[item] = element;
element.dom = item;
// using it in generic "onchange" trigger
function changeTrigger(e) {
var el = doms[e.target];
....
};
are there any dangers lurking in this approach?
Object keys are strings. So, when you try to use a DOM object as an object key, it will call toString() on the DOM object and use that as the key. toString() on DOM objects returns non-unique things like this:
[object HTMLParagraphElement]
So, it won't cause an error, but it probably won't do what you want. It would probably make more sense to use the object's ID as the key and generate a unique ID to put on the object if the object doesn't already have an id.
As best I can tell, any use of using an object as a key can also be done with the id as a key.
When I run this in Firefox 10:
window.onload = function(){
var doms = {},
item,
element = {
tag: 'input',
name: 'email',
value: null,
dom: null
};
for (var i = 0; i < 10; i++) {
item = document.createElement(element.tag);
item.name = element.name + i;
document.body.appendChild(item);
doms[item] = element;
}
console.log(doms);
};
I see the following in Firebug's console:
Object { [object HTMLInputElement]={...}}
Which expands to:
[object HTMLInputElement] Object { tag="input", name="email", value=null, more...}
dom null
name "email"
tag "input"
value null
http://jsbin.com/efuluk/
Note, there's only one reference/object pair, not ten. I suspect you can't do this, and I would advise against it anyways (in lieu of a specific citation supporting my hunch).

Categories