简体   繁体   中英

How to add data to a 2-D map in Javascript

I mostly develop in Java, but I presently need to do some work using JavaScript.

I have data that I need to group by two dimensions: first by gender, and then by language. The object to be grouped comes like so:

var items =[ {
  "language":"english",
  "gender":"male",
  ...//twelve other fields
},
...
]

This is what I've tried:

var myMap = {};
for(var i=0; i<items.length;i++){
  var item = items[i];
  var _gender = item["gender"];
  var _lang = item["language"];
  myMap[_gender][_lang].push[item];
}

I assumed the above would work, but it's not working. It keeps returning this error:

Uncaught TypeError: Cannot read property 'undefined' of undefined

Note: In Java, I would be creating a map of arrays.

You are doing totally wrong. First of all myMap is object not an array so you can not use myMap.push() . You can achieve like this.

var items = {
  "language":"english",
  "gender":"male"
}
var myMap = {};
for(var key in items){
   var myArray = [];
   var _gender = items["gender"];
   var _lang = items["language"];
   myArray.push(_gender);
   myArray.push(_lang);
   myMap.item = myArray;
   console.log(myMap);
}

for add 2-d array read this. 2-D Array in javascript

One problem:

When you call myMap[_gender][_lang].push[item]; , what you are actually doing is adding a key to the Object myMap , with the current value of _gender , and turning it into an Object, which you then create a new key for, set to the value of _lang . In addition, .push() is a function used with arrays , to add a new item onto the end of the array. If you want to add a new key and value to an Object, all you have to do is just call that key and assign it a value. Here's an example.

 var obj = { ex1 : 'example 1', ex2 : 'example 2' }; console.log(obj); obj.ex3 = 'example 3'; console.log(obj); //The code below will simply log 'undefined' in most consoles(it doesn't happen to do so in this snippet). console.log(obj.ex4); 

Here's my suggestion(assuming I correctly understand what you're trying to do):

 var items = [{ "language":"english", "gender":"male", }, //...more below ]; myMap = []; for(var i = 0; i < items.length; i++){ myArray = []; var item = items[i]; var _gender = item["gender"]; var _lang = item["language"]; myArray.push(_gender); myArray.push(_lang); myMap.push(myArray); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM