最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

hashmap - How can I print out a hash map's values as a string in JavaScript? - Stack Overflow

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

I have a map that I would like to print out in the following format:

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

Instead I get this. Each of those objects contains the list of strings that I would like to print above. How can I do this?

customer1|[object Object]
customer2|[object Object]
customer3|[object Object]
customer5|[object Object]
customer4|[object Object]
customer6|[object Object]
customer7|[object Object]
for (var i = 0, keys = Object.keys(map), ii = keys.length; i < ii; i++) {
  console.log(keys[i] + '|' + map[keys[i]]);
}

I have a map that I would like to print out in the following format:

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

Instead I get this. Each of those objects contains the list of strings that I would like to print above. How can I do this?

customer1|[object Object]
customer2|[object Object]
customer3|[object Object]
customer5|[object Object]
customer4|[object Object]
customer6|[object Object]
customer7|[object Object]
Share Improve this question asked Aug 29, 2017 at 12:06 Martin ErlicMartin Erlic 5,66726 gold badges91 silver badges162 bronze badges 1
  • Can you provide the map that is used, or an example map with the same structure? Without it, it is very hard to pinpoint the problem. – Thijs Commented Aug 29, 2017 at 12:11
Add a ment  | 

3 Answers 3

Reset to default 3

Try the normal forEach loop and use it this way:

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]);
});

Never mind. I found the answer. I need to print the list.

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

you can so something like this:

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);

Hope it helps!

发布评论

评论列表(0)

  1. 暂无评论