angular2 create an associative array
Solution 1
You can use a Map, but I'd opt into a plain object;
Demo
const mything = {}
mything.foo = 1
mything.foo === mything['foo'] // true
mything['bar'] = 1337;
mything.bar === 1337 // true
mything.foo-bar = 1 // ERROR: can't have dashes
mything['foo-bar'] = 1 // Works
In ES6, or any relatively modern browser, you can get all the keys by using Object.keys(mything)
. For older environments you're gonna have to loop over the keys using for ... in
as demonstrated in this polyfill: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Another thing you have to be careful of is having the previous item defined in your property chain. For example if you have
var foobar = {
foo: { bar: 1 }
}
then you CAN do foobar.foo.bar.toString()
to get "1"
, but if you try to do foobar.foo.bang.toString()
you'll get an error cause bang
is not defined on the foo
object.
You can resolve this by doing a guard check like foobar.foo.bang && foobar.foo.bang.toString()
which will only run the toString method if bang exists.
The easier way to do this would be to use lodash
which gives you the _.get
, and _.set
which take care of the guards and the creation of the missing properties respectively.
Solution 2
Javascript does not have associate array, just use {}
or new Map
api
let xxxMap = new Map();
xxxMap.set('key1', 'value 1');
xxxMap.set('key2', 5);
console.log(xxxMap.get('key1'));
learn more from there: Map in Javascript
Geoff
A coder who loves taking coffee, sleeping in the morning but working late at night
Updated on June 14, 2022Comments
-
Geoff almost 2 years
I would like to create an associative array in angular2 but havent found out a way yet
This is what i have tried
onSubmit(){ let inputfield:any[] = []; for(var i=0; i<this.inspectionform.value["inputfileds"].length; i++){ if(this.inspectionform.value["inputfileds"][i]["input"] != ""){ //here i need help inputfield.push( i : this.inspectionform.value["inputfileds"][i]["input"]) //this returns a syntax error } }
} So what am actually looking forward to have is to pass a key and value to the array
Something like
1:sdbhd//pass this to the array
In the for loop i have tried
//inside the for loop let arrayval = []; arrayval.push(this.inspectionform.value["inputfileds"][i]["input"]) arrayval.push(i) inputfield.push(arrayval);
This creates a new object every time of this nature
0:njnf 1:1(value of i)