2

I am just starting to use associative arrays in JavaScript. I kind of understand that they are not really arrays, but they seem to serve my purpose, which is to load some configuration data from records into some session scope variables so I can very easily access them.

Now I have a data structure which can have multiple values for each key. I am having trouble loading this up.

Below is some pseudo-code. It runs through a loop, loading an associative array such that I will have the following:

key="App1" values="App1Title1,App1Title2,etc" key="App2" values="App2Title1,App2Title2,etc"

What is the best way to do this?

var tmpDes = {};

//Loop through data records
//Load the values below from loop, not hardcoded like here.
var keyStr:String = "key";
var valStr1:String = "value1";
var valStr2:String = "value2";


//This seems to work 
tmpDes[tmpStr] = "xpApp1Title1";
tmpDes[tmpStr] = tmpDes[tmpStr] + "," + tmpStr1;

// 

========================================================= These are excellent answers. I did realize from searching around that these are not really associative arrays but objects, I should of mentioned that.

Dan, the problem is I am in a loop through a table of docs, so I do not know valStr1 and valStr2 when I am constructing the js object. What I want in essence is to use "push" but these are not really arrays, so that will not work.

===================================================

This is closer but the problem is that I do not know the values that will be coming from the documents, and I do not understand how to make the array name come from a variable.

Documents in file contain these fields

KEY VALUE App1 App1Title1 App1 App1Title2 App2 App2Title1 App2 App2Title2 etc.

I need to create a structure so that if I call App1 I can get a list ==> "App1Title1":"App1Title2"

So I create my object and temp string variables, then start reading docs.

Load temp variables from first doc.

Then I want to set the obj. But I want to do that dynamically.

so the line

obj.tmpKey.push(tmpVal) 

should execute

obj.App1.push(AppTitle1). 

but obviously how I have written it it won't work it loads tmpKey with tmpVal

Maybe I am using the wrong structure? I am open to changing it.

var obj = {};

var tmpKey:String;
var tmpVal:String

//Loop docs, getting values.

tmpKey = doc.getItemValueString("var1");
tmpVal = doc.getItemValueString("var2");

obj.tmpKey.push(tmpVal);

//Loop
2
  • I see from your setting type with your variable names and also your tags, you're using XPages SSJS. Your working with the object will be nearly identical to normal JS objects (as Breedly answered below). So you can use dot and bracket notation as normal. When that object gets set into viewScope (any *Scope var), it's set into a Java map, causing a transform into an ObjectObject, which Tim talked about in a different SO answer. Think of it like another map. Commented Jul 16, 2015 at 19:15
  • 1
    Re: your update, normal dot notation and bracket notation allow "pushing" of a new keyed value into an object. Since JS doesn't have "type" enforcing on objects; its definition is all "runtime defined", if you will. So, if you need to check if a key exists in an object, the Object.prototype.hasOwnProperty() method is the ideal way to do this in JS. So either if check your keys for existing vals or arbitrarily set the key/value pairs. Commented Jul 18, 2015 at 0:38

2 Answers 2

3

This is not an associative array. In Javascript we call this an Object, which is a different thing, though you can often use them similarly to what other languages call an associative array, hash, or dictionary.

An Object has properties (which are like keys). You can store arrays (and other types) as the value of an Object property.

var obj = {};

obj.aThing = [];
obj.anotherThing = [];

obj.aThing.push("foo");
obj.aThing.push("bar");

obj.anotherThing.push("a");
obj.anotherThing.push("b");
obj.anotherThing.push("c");

console.log("aThing", obj.aThing);
console.log("anotherThing", obj.anotherThing);

will produce as output:

aThing [ "foo", "bar" ]
anotherThing [ "a", "b", "c" ]

You mention that you need to make the property name come from a variable, which Javascript also allows for. You need to use objectName[varName] instead, as in this example.

var obj = {};

var name1 = "aThing";
var name2 = "anotherThing";

obj[name1] = [];
obj[name2] = [];

obj[name1].push("foo");
obj[name1].push("bar");

obj[name2].push("a");
obj[name2].push("b");
obj[name2].push("c");

console.log(name1, obj[name1]);
console.log(name2, obj[name2]);

It's the same code just using variables as the object keys.

Finally, you can use strings directly for property names.

var obj = {};

obj["aThing"] = [];
obj["anotherThing"] = [];

obj["aThing"].push("foo");
obj["aThing"].push("bar");

obj["anotherThing"].push("a");
obj["anotherThing"].push("b");
obj["anotherThing"].push("c");

console.log("aThing", obj["aThing"]);
console.log("anotherThing", obj["anotherThing"]);
Sign up to request clarification or add additional context in comments.

5 Comments

Dan, please see my comment above.
@BryanSchmiedeler I edited the answer to explain it better in the context of using .push().
Dan, I have responded above.
@BryanSchmiedeler ah, I see - I edited my answer to show how to use variables instead of strings, to access the object keys.
Dan, extremely helpful. I appreciate it very much. I learned a lot from this question. And your answers allowed me to solve my problem.
3

In JavaScript we call associative arrays Objects, everything in JS is an Object even Functions.

I'll run you through some stuff.

First off, when declaring an Object this is the preferred method.

var obj = {
 key: 'value', //Any object or value can be used here.
}

I can then access this in various manners.

Dot Notation (Preferred):

obj.key === 'value' //True

Array Notation (When You're Desperate):

obj['key'] === 'value' //True

Array Notation is often used when you want to have a key that breaks the JS Variable Naming Syntax such as:

var headers = {
 'Content-Type': 'application/json'
}

headers['Content-Type'] === 'application/json' //True

Or you're looping through an array of Object keys.

var keys = Object.keys(headers);

keys.forEach(function(key) {
  console.log(headers[key]);
});

There are tons of things you can with Objects, read the MDN Docs on this and many other JS Objects for good info.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.