jQuery Get associative array Key from index - javascript

My question is the following, in an array:
var array = new Array();
array['abc'] = 'value1';
array['def'] = 'value2';
How do I get the associative key of an array if I have its index number? Let's say I want associative key of arr[0]'s associative key ( => 'abc'), or associative key of arr[1] '=> 'def'). How is this possible in jQuery?
Let's be clear, I am not looking for the value and I do not need to use $.each(). I just need to link 0 to 'abc' and 1 => 'def' etc... Unfortunately something like arr[0].assoc_key() doesn't seem to exist T_T
Thanks a bunch.

All right so the solution is pretty simple, you need to create an object which associates indeces with keys as well as keys with values. Here is a JSBin that works. Please note that to add an element, you need a custom function (addElement in this case) to be able to have both indeces and keys associated at the right places. This is a rough draft to give you an idea of how it can be done!
JSBin
If you have any question or if that wasn't exactly what you expected, simply edit your question and I'll have another glance at it. It HAS to be a custom made object if you want the behavior you asked for.

Javascript doesn't have a native Dictionary type, you would have to write it. – T McKeown
It isn't possible and jQuery doesn't come into the picture at all. If you use an array as a dictionary like that, you are doing something wrong. – Jon
rethink the way you are doing it. Maybe try array[0] = {key: 'abc', value: 'value1'} – Geezer68
#Geezer68, objects do not support multidimentional data, the array I'm working on is 3 levels deep (I know I didn't says so in my original post, but I didn't think it was relevant).
Anyway, thank you guys, it answers the question! I will rethink it then ;-)
EDIT: I guess I'll just add a level:
var array = new Array();
array[] = 'abc';
array[0] = 'value1'

I don't know an other than using a for ... in. So here how i do it and hope you get a better answer (because i want to know aswell!).
var array = new Array();
array['abc'] = 'value1';
array['def'] = 'value2';
var listKeys = [];
for(x in array) listKeys.push(x);
console.log(listKeys); // ['abc', 'def']
but using [string] on an array object is adding property to the object, not the array. So it may be better to initialise it like that :
var array = {};
You might learn more information on this technique in this question and some restriction on why you should not rely on that.

Related

Get value from Json object with unique key

How do I check if a JSON object have key are duplicate, just get distint the key and not use foreach function? Such as:
var objectData = {[value1: abc], [value1: abc], [value2: bcd]}
If a key doesn't exist, and I try to access it, will it return undefined? Or get the error?
If this is meant to be an array of JSON objects:
var objectData = [ {"value1": "abc"}, {"value1": "abc"}, {"value2": "bcd"} ];
Then your answer lies within the responses to this question: Remove duplicates from an array of objects in javascript or this one Remove duplicate objects from an array using javascript.
If your notation accurately reflects what is produced by your system (or your own coding), you may want to rework it a bit so it makes sense.
Hope that helps.

Javascript object/array manipulation

Struggling with some javascript array manipulation/updating. Hope someone could help.
I have an array:
array('saved_designs'=array());
Javascript JSON version:
{"saved_design":{}}
I will be adding a label, and associated array data:
array("saved_designs"=array('label'=array('class'='somecssclass',styles=array(ill add more assoc elements here),'hover'=array(ill add more assoc elements here))))
Javascript version:
{"saved_designs":{"label":{"class":"someclass","style":[],"hover":[]}}}
I want to be able to append/modify this array. If 'label' already defined...then cycle through the sub data for that element...and update. If 'label' doesnt exist..then append a new data set to the 'saved_designs' array element.
So, if label is not defined, add the following to the 'saved_designs' element:
array('label2' = array('class'=>'someclass2',styles=array(),'hover=>array()')
Things arent quite working out as i expect. Im unsure of the javascript notation of [], and {} and the differences.
Probably going to need to discuss this as answers are provided....but heres some code i have at the moment to achive this:
//saveLabel = label the user chose for this "design"
if(isUnique == 0){//update
//ask user if want to overwrite design styles for the specified html element
if (confirm("Their is already a design with that label ("+saveLabel+"). Overwrite this designs data for the given element/styles?")) {
currentDesigns["saved_designs"][saveLabel]["class"] = saveClass;
//edit other subdata here...
}
}else{//create new
var newDesign = [];
newDesign[saveLabel] = [];
newDesign[saveLabel]["class"] = saveClass;
newDesign[saveLabel]["style"] = [];
newDesign[saveLabel]["hover"] = [];
currentDesigns["saved_designs"].push(newDesign);//gives error..push is not defined
}
jQuery("#'.$elementId.'").val(JSON.stringify(currentDesigns));
thanks in advance. Hope this is clear. Ill update accordingly based on questions and comments.
Shaun
It can be a bit confusing. JavaScript objects look a lot like a map or a dictionary from other languages. You can iterate over them and access their properties with object['property_name'].
Thus the difference between a property and a string index doesn't really exist. That looks like php you are creating. It's called an array there, but the fact that you are identifying values by a string means it is going to be serialized into an object in javascript.
var thing = {"saved_designs":{"label":{"class":"someclass","style":[],"hover":[]}}}
thing.saved_designs.label is the same thing as thing["saved_designs"]["label"].
In javascript an array is a list that can only be accessed by integer indices. Arrays don't have explicit keys and can be defined:
var stuff = ['label', 24, anObject]
So you see the error you are getting about 'push not defined' is because you aren't working on an array as far as javascript is concerned.
currentDesigns["saved_designs"] == currentDesigns.saved_designs
When you have an object, and you want a new key/value pair (i.e. property) you don't need a special function to add. Just define the key and the value:
**currentDesigns.saved_designs['key'] = newDesign;**
If you have a different label for every design (which is what it looks like) key is that label (a string).
Also when you were defining the new design this is what javascript interprets:
var newDesign = [];
newDesign is an array. It has n number of elements accessed by integers indices.
newDesign[saveLabel] = [];
Since newDesign is a an array saveLabel should be an numerical index. The value for that index is another array.
newDesign[saveLabel]["class"] = saveClass;
newDesign[saveLabel]["style"] = [];
newDesign[saveLabel]["hover"] = [];
Here explicitly you show that you are trying to use an array as objects. Arrays do not support ['string_key']
This might very well 'work' but only because in javascript arrays are objects and there is no rule that says you can't add properties to objects at will. However all these [] are not helping you at all.
var newDesign = {label: "the label", class: saveClass};
is probably what you are looking for.

Create an array of JavaScript objects from an existing array of objects

my first time posting a question here, so please let me know if I'm missing any information that is needed. Updated to include desired output.
I'm working on a google app script (basically javascript) and am trying to pull objects from an array of objects and create a new array of objects. I'm using the google base functions for getRowData (these can be found at : https://developers.google.com/apps-script/guides/sheets) to create my initial array of objects. This gives me a row of data similar (A JIRA export if anyone is wondering, with information cut):
{summary=Internal - Fix PuppetFile Jenkins Jobs, progress=1.0, issueType=Story, resolution=Done, timeSpent=3600.0, key=XXXXX-646, watchers=0.0, remainingEstimate=0.0, numberOfComments=1.0, status=Resolved, assignee=XXXXXXXX}
When I run my function:
for (var i = 0; i < issueList.length; i++){
rankList[i] = [issueList[i].summary,issueList[i].storyPoints,issueList[i].epicLink,issueList[i].fixVersions];
}
I get:
[Internal - Fix PuppetFile Jenkins Jobs, 3.0, null, null]
But what I want is:
{summary=Internal - Fix PuppetFile Jenkins Jobs, storyPoints=1.0, epicLink=StoryName, fixVersions=Done}
I'm not getting the key for the value, and I don't understand how the objects are constructed quite well enough to get it to transfer over. I looked at some examples of manipulating the key/value pairs but when I tried it on my own I just got a bunch of undefined. Thank you for any help you can provide.
What you want is probably something like this:
rankList = [];
for (var i = 0; i < issueList.length; i++) {
issue = issueList[i];
rankList.push({
summary: issue.summary,
storyPoints: issue.progress,
epicLink: issue.IDONTKNOW,
fixVersions: issue.resolution
});
}
I don't know what field goes in epicLink, since it wasn't obvious from your example. And I was just guessing about the other fields. But this is the general structure, you just need to make all the correct correspondences.
Use jquery each instead it's much easier to get the keys and value at the same time:
var myarray = [];
$.each(issueList,function(key,value){
console.log(key);
console.log(value);
value.key = key;
myarray.push(value);
});
console.log(myarray);

Javascript pushing objects into array changes entire array

I'm using a specific game making framework but I think the question applies to javascript
I was trying to make a narration script so the player can see "The orc hits you." at the bottom of his screen. I wanted to show the last 4 messages at one time and possibly allow the player to look back to see 30-50 messages in a log if they want. To do this I set up and object and an array to push the objects into.
So I set up some variables like this initially...
servermessage: {"color1":"yellow", "color2":"white", "message1":"", "message2":""},
servermessagelist: new Array(),
and when I use this command (below) multiple times with different data called by an event by manipulating servermessage.color1 ... .message1 etc...
servermessagelist.push(servermessage)
it overwrites the entire array with copies of that data... any idea why or what I can do about it.
So if I push color1 "RED" and message1 "Rover".. the data is correct then if I push
color1"yellow" and message1 "Bus" the data is two copies of .color1:"yellow" .message1:"Bus"
When you push servermessage into servermessagelist you're really (more or less) pushing a reference to that object. So any changes made to servermessage are reflected everywhere you have a reference to it. It sounds like what you want to do is push a clone of the object into the list.
Declare a function as follows:
function cloneMessage(servermessage) {
var clone ={};
for( var key in servermessage ){
if(servermessage.hasOwnProperty(key)) //ensure not adding inherited props
clone[key]=servermessage[key];
}
return clone;
}
Then everytime you want to push a message into the list do:
servermessagelist.push( cloneMessage(servermessage) );
When you add the object to the array, it's only a reference to the object that is added. The object is not copied by adding it to the array. So, when you later change the object and add it to the array again, you just have an array with several references to the same object.
Create a new object for each addition to the array:
servermessage = {"color1":"yellow", "color2":"white", "message1":"", "message2":""};
servermessagelist.push(servermessage);
servermessage = {"color1":"green", "color2":"red", "message1":"", "message2":"nice work"};
servermessagelist.push(servermessage);
There are two ways to use deep copy the object before pushing it into the array.
1. create new object by object method and then push it.
servermessagelist = [];
servermessagelist.push(Object.assign({}, servermessage));
Create an new reference of object by JSON stringigy method and push it with parse method.
servermessagelist = [];
servermessagelist.push(JSON.parse(JSON.stringify(servermessage));
This method is useful for nested objects.
servermessagelist: new Array() empties the array every time it's executed. Only execute that code once when you originally initialize the array.
I also had same issue. I had bit complex object that I was pushing in to the array. What I did; I Convert JSON object as String using JSON.stringify() and push in to the Array.
When it is returning from the array I just convert that String to JSON object using JSON.parse().
This is working fine for me though it is bit far more round solution.
Post here If you guys having alternative options
I do not know why a JSON way of doing this has not been suggested yet.
You can first stringify the object and then parse it again to get a copy of the object.
let uniqueArr = [];
let referencesArr = [];
let obj = {a: 1, b:2};
uniqueArr.push(JSON.parse(JSON.stringify(obj)));
referencesArr.push(obj);
obj.a = 3;
obj.c = 5;
uniqueArr.push(JSON.parse(JSON.stringify(obj)));
referencesArr.push(obj);
//You can see the differences in the console logs
console.log(uniqueArr);
console.log(referencesArr);
This solution also work on the object containing nested keys.
Before pushing, stringify the obj by
JSON.stringify(obj)
And when you are using, parse by
JSON.parse(obj);
As mentioned multiple times above, the easiest way of doing this would be making it a string and converting it back to JSON Object.
this.<JSONObjectArray>.push(JSON.parse(JSON.stringify(<JSONObject>)));
Works like a charm.

Test for value within array of objects

I am dynamically building an array of objects using a process that boils down to something like this:
//Objects Array
var objects = [];
//Object Structure
var object1 = {"id":"foobar_1", "metrics":90};
var object2 = {"id":"some other foobar", "metrics":50};
objects[0] = object1;
objects[1] = object2;
(Let it be said for the record, that if you can think of a better way to dynamically nest data such that I can access it with objects[i].id I am also all ears!)
There's ultimately going to be more logic at play than what's above, but it's just not written yet. Suffice it to say that the "object1" and "object2" parts will actually be in an iterator.
Inside that iterator, I want to check for the presence of an ID before adding another object to the array. If, for example, I already have an object with the ID "foobar_1", instead of pushing a new member to the array, I simply want to increment its "metrics" value.
If I wasn't dealing with an array of objects, I could use inArray to look for "foobar_1" (a jQuery utility). But that won't look into the object's values. The way I see it, I have two options:
Keep a separate simple array of just the IDs. So instead of only relying on the objects array, I simply check inArray (or plain JS equivalent) for a simple "objectIDs" array that is used only for this purpose.
Iterate through my existing data object and compare my "foobar_1" needle to each objects[i].id haystack
I feel that #1 is certainly more efficient, but I can't help wondering if I'm missing a function that would do the job for me. A #3, 4, or 5 option that I've missed! CPU consumption is somewhat important, but I'm also interested in functions that make the code less verbose whether they're more cycle-efficient or not.
I'd suggest switching to an object instead of an array:
var objects = {};
objects["foobar_1"] = {metrics: 90};
objects["some other foobar"] = {metrics: 50};
Then, to add a new object uniquely, you would do this:
function addObject(id, metricsNum) {
if (!(id in objects)) {
objects[id] = {metrics: metricsNum};
}
}
To iterate all the objects, you would do this:
for (var id in objects) {
// process objects[id]
}
This gives you very efficient lookup for whether a given id is already in your list or not. The only thing it doesn't give you that the array gave you before is a specific order of objects because the keys of an object don't have any specific order.
Hmm , i wonder why dont you use dictionary cause that is perfectlly fits your case. so your code will be as below:
//Objects Array
var objects = [];
//Object Structure
var object1 = {"metrics":90};
var object2 = {"metrics":50};
objects["foobar_1"] = object1;
objects["some other foobar"] = object2;
// An example to showing the object existence.
if (!objects["new id"]){
objects["new id"] = {"metrics": 100};
}
else {
objects["new id"].matrics++;
}

Categories

Resources