如何在JavaScript中将哈希映射的值打印为字符串?

时间:2017-08-29 12:06:05

标签: javascript hashmap

>>> import datetime
>>> datetime.datetime.now().strftime("%a, %d %B %Y %H:%M:%S")
'Tue, 29 August 2017 03:04:21'

我有一张地图,我想用以下格式打印出来:

for (var i = 0, keys = Object.keys(map), ii = keys.length; i < ii; i++) {
  console.log(keys[i] + '|' + map[keys[i]]);
}

相反,我得到了这个。每个对象都包含我想在上面打印的字符串列表。我怎么能这样做?

customer1|asdfasdf,asdfasdf,asdfa
customer2|adf
customer3|asdf,rthrg
customer5|dfgbdf
customer4|bfdgbfg,bdfgb,dfgb
customer6|sdfgf
customer7|xcvb,xvcbff

3 个答案:

答案 0 :(得分:0)

没关系。我找到了答案。我需要打印清单。

for (var i = 0, keys = Object.keys(map), ii = keys.length; i < ii; i++) {
  console.log(keys[i] + '|' + map[keys[i]].list);
}

答案 1 :(得分:0)

你可以这样:

&#13;
&#13;
function printKeys(map){
	for (var i = 0, keys = Object.keys(map), ii = keys.length; i < ii; i++) {
		val = map[keys[i]];
		if(typeof val === 'object'){
			printKeys(val);
		}else{
			console.log(keys[i] + '|' + map[keys[i]]);
		}
	}
}

map = {a :1, b:2, c:3, d: {d1: 4}};
printKeys(map);
&#13;
&#13;
&#13;

希望它有所帮助!

答案 2 :(得分:0)

尝试正常的forEach循环并以这种方式使用它:

&#13;
&#13;
var cust = {
  customer1: ["cus1Value1", "cus1Value2", "cus1Value3"],
  customer2: ["cus2Value1", "cus2Value2", "cus2Value3", "cus3value4"],
  customer3: ["cus3Value1", "cus3Value2"],
  customer4: ["cus4Value1", "cus4Value2"],
  customer5: ["cus5Value1", "cus5Value2"]
};

var keys = Object.keys(cust);
keys.forEach(key=>{
  console.log(key + '|' + cust[key]);
});
&#13;
&#13;
&#13;