Related
I'm trying to understand what an associative array really is and what steps are needed to acquire one. I have seen many explanations that are totally different.
I have tried testing it out on my own but can't seem to really get it in the end.
var array = ["one", "two", "three"];
var test = array["one"];
console.log(test);
I expected for it to target the index in which the string "one" is in, but an error occurs.
You are likely looking for a JavaScript Object, what is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. Unlike Arrays, which use square brackets [] for declaration, Objects use curly braces {} (please note that there are some exceptions).
Try to think of an Object as an associative array:
const arr = {one: 1, two: 2, three: 3};
console.log(arr['one']);
console.log(arr.one);
It is worth noting that Array's in JavaScript are technically objects.
The JavaScript Array object is a global object that is used in the construction of arrays; which are high-level, list-like objects.
The main difference between Array's and Object's is that Arrays are numerically indexed.
const arr = ['fooValue', 'barValue'];
const obj = {foo: 'fooValue', bar: 'barValue'};
console.log('arr: ', arr[0], arr[1]);
console.log('obj: ', obj.foo, obj.bar);
It is worth noting, that unlike primitive types in JavaScript, Object's (and Array's, which are also Object's) are passed by reference, so extra care is needed when attempting to copy the object.
function test(obj) {
obj['oops'] = 'this will modify the object';
}
const obj = {one: 1, two: 2, three: 3};
test(obj);
console.log(obj); // Object was updated
To avoid accidentally mutating your object, you will have to create a new instance of the object before performing operations on it. There are multiple ways to accomplish this:
Destructuring/spreading you object let obj2 = {...obj};
Using Object.assign()
I'm trying to understand what an associative array really is...
JavaScript doesn't have associative arrays in the sense that, for instance, PHP does. JavaScript has:
Arrays, which are (effectively) numerically indexed (see my blog post for why I said "effectively")
Objects, which are collections of properties that have names, which are either strings or Symbols (and which have other features, like inheritance)
Maps, which are collections of key/value pairs where the keys can be any type (not just strings or Symbols)
Arrays
To find the index of an entry in an array, typically you use indexOf (for an === match) or findIndex if you want to provide a predicate function.
var array = ["one", "two", "three"];
console.log(array.indexOf("one")); // 0
Objects
If you wanted, you could create an object that mapped strings to numbers:
var obj = {"one": 1, "two": 2, "forty-two": 42};
console.log(obj["forty-two"]); // 42
Maps
Similarly, a Map could do that:
var map = new Map([
["one", 1],
["two", 2],
["forty-two", 42]
]);
console.log(map.get("forty-two")); // 42
Associative arrays are used to associate something throughout an array.
You can use this with the query string for example:
In order to attain the information from a forum submitted, you need to put the user data into an associative array.
You would start by getting the query string as follows:
var queryString = window.location.search;
queryString = queryString.substring(1);
The reason why I did substring(1) is so we could remove the '?' at the beginning.
Once you have the query string of the website, you'd need a loop to separate the values of data received:
while (queryString.indexOf("+") != -1)
queryString = queryString("+", " ");
This will replace all the '+' signs in the string to spaces, making you get the values without the '+' signs. You'll have "Name=John" for example.
Now we need to split the '&'s from the string.
We also need to make an array ready for the data from the user.
var array = queryString.split("&");
var userData = [];
Afterwards, make a for loop in order to target however amount of data submitted and to attain it individually while storing it into the array:
for (let x = 0; x < array.length; x++)
{
var equalSign = array[x].search("=");
var theKeyValue = array[x].substring(0, equal);
var userDataValue = array[x];
userDataValue = decodeURIComponent(userDataValue); //Puts symbols back
userData[theKeyValue] = userDataValue;
}
This is just an example to follow up with the usage of associative arrays, hopefully this helps. :)
See Wikipedia.
It is a data structure when you can look up a value by a key. This is typically implemented in JS using a Map or an Object.
const data = new Map([
['foo', 'one'],
['bar', 'two']
]);
console.log( data.get("bar") );
I expected for it to target the index in which the string "one" is in, but an error occurs.
You are attempting to look up the index of a property in an array by its value.
That has nothing to do with associative arrays and is achieved with the indexOf method.
var array = ["one", "two", "three"];
var test = array.indexOf("one");
console.log(test);
An associative array, is essentially a hashmap, or an array that associates relationships.
For example if I was to build an associative array for fruits let's say to prices it would look like.
const arr = {'apple': 1, 'orange': 2, 'pear': 3};
console.log(Object.keys(arr));
console.log(Object.values(arr));
Unlike other languages, array in Javascript are not limited by having only numeric indices. They can act as hashes as well (i.e. having a string as a key). An associative array is one where you set the key to be a non-numeric value.
By default, and in the example you provided, ascending numeric values are assigned to each member of the array. I.e.
var array = ["one", "two", "three"];
is equivalent to
var array = [];
array[0] = 'one';
array[1] = 'two';
array[2] = 'three';
An associative array would be one where instead of numeric values you assign a different value:
var array = [];
array['one'] = 'one';
array['two'] = 'two';
However this brings a few caveats in itself and it considered bad practice and the arrays become harder to manage. In cases like there it would be better to use either an object or a Map.
An associative array is a data structure, a data collection, which has the scope of associate a list of key to respective values (key: value).
You can read in Wikipedia here, that are example of associative array for example: Map, Dictionary, etc.
Sample of associative array are also PHP indexed array, e.g.:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
That's not an associative array, that's just a regular array, filled with text.
An associative array example (you can also use object syntax like Miroslav's answer):
var stuff = [];
stuff['one'] = "hello 1";
stuff['two'] = "hello 2";
This is the array:
{"C8_235550":
{"listing":"aut,C8_235550_220144650654"},
"C8_231252":
{"listing":"aut,C8_231252_220144650654"}}
It was fetched with a GET request from a Firebase database using Google Apps Script.
var optList = {"method" : "get"};
var rsltList = UrlFetchApp.fetch("https://dbName.firebaseio.com/KeyName/.json", optList );
var varUrList = rsltList.getContentText();
Notice the .getContentText() method.
I'm assuming that the array is now just a string of characters? I don't know.
When I loop over the returned data, every single character is getting pushed, and the JavaScript code will not find key/value pairs.
This is the FOR LOOP:
dataObj = The Array Shown At Top of Post;
var val = dataObj;
var out = [];
var someObject = val[0];
for (var i in someObject) {
if (someObject.hasOwnProperty(i)) {
out.push(someObject[i]);
};
};
The output from the for loop looks like this:
{,",C,8,_,2,3,5,5,5,0,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,5,5,5,0,_,2,2,0,1,4,4,6,5,0,6,5,4,",},,,",C,8,_,2,3,1,2,5,2,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,1,2,5,2,_,2,2,0,1,4,4,6,5,0,6,5,4,",},}
I'm wondering if the array got converted to a string, and is no longer recognized as an array, but just a string of characters. But I don't know enough about this to know what is going on. How do I get the value out for the key named listing?
Is this now just a string rather than an array? Do I need to convert it back to something else? JSON? I've tried using different JavaScript array methods on the array, and nothing seems to return what it should if the data was an array.
here is a way to get the elements out of your json string
as stated in the other answers, you should make it an obect again and get its keys and values.
function demo(){
var string='{"C8_235550":{"listing":"aut,C8_235550_220144650654"},"C8_231252":{"listing":"aut,C8_231252_220144650654"}}';
var ob = JSON.parse(string);
for(var propertyName in ob) {
Logger.log('first level key = '+propertyName);
Logger.log('fisrt level values = '+JSON.stringify(ob[propertyName]));
for(var subPropertyName in ob[propertyName]){
Logger.log('second level values = '+ob[propertyName][subPropertyName]);
}
}
}
What you have is an object, not an array. What you need to do is, use the
Object.keys()
method and obtain a list of keys which is the field names in that object. Then you could use a simple for loop to iterate over the keys and do whatever you need to do.
I am using the following script to help me convert javascript arrays to json strings: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
How come this works:
var data = [];
data[1] = [];
data[1].push('some info');
data[1].push('some more info');
json_data = JSON.stringify(data);
alert(json_data);
And this does not (returns a blank):
var data = [];
data['abc'] = [];
data['abc'].push('some info');
data['abc'].push('some more info');
json_data = JSON.stringify(data);
alert(json_data);
I want to convert multi-dimensional javascript arrays, but it seems I cannot use stringify() if I name my array keys?
JSON arrays are integer-indexed only.
You can change your first line to use {} as in http://jsfiddle.net/5YXNk/, which is the best you can do here.
Check the array syntax at http://json.org/ -- note arrays contain values only, which will be implicitly indexed by non-negative integers. That's just the way it is.
There is no such thing as an associative array in Javascript. You're going to have to use an object if you want to use string "keys".
I am kind of new to the world of interface, and i found JSON is amazing, so simple and easy to use.
But using JS to handle it is pain !, there is no simple and direct way to push a value, check if it exists, search, .... nothing !
and i cannot simply add a one single value to the json array, i have this :
loadedRecords = {}
i want to do this :
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
Why this is so hard ???!!!
Because that's an object, not an array.
You want this:
var = loadedRecords = []
loadedRecords.push('1234');
Now to your points about JSON in JS:
there is no simple and direct way to push a value
JSON is a data exchange format, if you are changing the data, then you will be dealing with native JS objects and arrays. And native JS objects have all kinds of ways to push values and manipulate themeselves.
check if it exists
This is easy. if (data.someKey) { doStuff() } will check for existence of a key.
search
Again JSON decodes to arrays and objects, so you can walk the tree and find things like you could with any data structure.
nothing
Everything. JSON just translates into native data structures for whatever language you are using. At the end of the day you have objects (or hashes/disctionaries), and arrays which hold numbers strings and booleans. This simplicity is why JSON is awesome. The "features" you seek are not part of JSON. They are part of the language you are using to parse JSON.
Well .push is an array function.
You can add an array to ur object if you want:
loadedRecords = { recs: [] };
loadedRecords.recs.push('654654');
loadedRecords.recs.push('11');
loadedRecords.recs.push('3333');
Which will result in:
loadedRecords = { recs: ['654654', '11', '3333'] };
{} is not an array is an object literal, use loadedRecords = []; instead.
If you want to push to an array, you need to create an array, not an object. Try:
loadedRecords = [] //note... square brackets
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
You can only push things on to an array, not a JSON object. Arrays are enclosed in square brackets:
var test = ['i','am','an','array'];
What you want to do is add new items to the object using setters:
var test = { };
test.sample = 'asdf';
test.value = 1245;
Now if you use a tool like FireBug to inspect this object, you can see it looks like:
test {
sample = 'asdf,
value = 1245
}
Simple way to push variable in JS for JSON format
var city="Mangalore";
var username="somename"
var dataVar = {"user": 0,
"location": {
"state": "Karnataka",
"country": "India",
},
}
if (city) {
dataVar['location']['city'] = city;
}
if (username) {
dataVar['username'] = username;
}
Whats wrong with:
var loadedRecords = [ '654654', '11', '333' ];
I am using array as an associative array of objects in which keys are ID number of objects in database. Quiet naturally- IDs are large numbers - so that means it is common to have array of length 10^4 with only 20 elements as valid real objects.
I want to send this data back to server but whatever plugins I had to convert js objects to JSON- I tried them all & they all produce a JSON string of length 10^4. So much data can't be sent back.
I need a way of converting associative array to JSON discarding undefined entries.
Any suggestions ?
EDIT:
Example of what my array looks like :
var myAssociativeArray = [undefined, undefined,undefined...., someobject, some other object ...,undefined, ... yet another....]
It sounds like you have a regular array, but you're using it as if it were sparse (which it may or may not be internally). Here's how to use a replacer function that will convert to an object:
JSON.stringify(root, function(k,v)
{
if(v instanceof Array)
{
var o = {};
for(var ind in v)
{
if(v.hasOwnProperty(ind))
{
o[ind] = v[ind];
}
}
return o;
}
return v;
});
Reading your question, it looks are using an array. Here's one solution to get only the defined entries of the array (order not guaranteed).
Note that since it is a sparse array and can go upto 10000 for instance, it's better to only enumerate the properties and not actually loop from 0 to 9999, as most of them will be undefined anyways. So this is better for performance.
var definedEntries = {};
for(var prop in dataObject) {
if(dataObject.hasOwnProperty(prop)) {
definedEntries[prop] = dataObject[prop];
}
}
Then send definedEntries to the server.