-2

我有以下字典:

{1:['a&b','b-c','c-d'],2:['e orf ','f-k-p','g']}

我想打印这本字典中的键和值,我尝试了以下代码:

for (var key in dictionary) {
    // check if the property/key is defined in the object itself, not in parent
    if (dictionary.hasOwnProperty(key)) {           
        console.log(key, dictionary[key]);
    }
}

我只是得到一些随机数。我该如何解决?我的输出:

key:34639values:mkey:34640values:akey:34641values:tkey:34642values:hkey:34643values:ekey:34644values:mkey:34645values:akey:34646values:tkey:34647values:ikey:34648values:ckey:34649values:skey:34650values: key:34651values:pkey:34652values:rkey:34653values:okey:34654values:bkey:34655values:lkey:34656values:ekey:34657values:mkey:34658values:

我希望输出为:

keys: 1,2
values: ['a&b','b-c','c-d'],['e orf ','f-k-p','g']

var dictionary = {1:['a','b','c'],2:['e','f','g']}
for (var key in dictionary) {
    // check if the property/key is defined in the object itself, not in parent
    if (dictionary.hasOwnProperty(key)) { 
        console.log(`key: `, key);
        console.log(`values: `, dictionary[key]);
    }
}

编辑:实际上字典被视为字符串。我怎样才能将它类型转换为字典?

4

4 回答 4

0

我运行了您的代码,这是输出:

在此处输入图像描述

于 2020-06-19T08:26:22.467 回答
0

您可以使用

Object.keys(dictionary)

这将导致: 两个元素的数组:["1", "2"]

当你有对象的键时,你可以使用简单的 for 循环来获取它的内容:

for(let key of Object.keys(dictionary))
    console.log(dictionary[key])

结果:

["a", "b", "c"]
["e", "f", "g"]

别忘了console.table(dictionary)。对于简单的表格结构,它可能有助于显示。

于 2020-06-19T08:38:30.303 回答
0

我创建了以下实用程序来满足您的要求。

let data = {1:['a&b','b-c','c-d'],2:['e orf ','f-k-p','g']}

const keys = Object.keys(data)
const values = Object.values(data)
console.log(`Keys: ${keys.join()}`)

let result = values.reduce((result, value) => { result.push(JSON.stringify(value)); return result}, []).join()
console.log(`Values: ${result}`)

希望这可以帮助。

于 2020-06-19T08:45:15.933 回答
0
var dictionary = {1:['a','b','c'],2:['e','f','g']}
var keys = [];
var values = [];
for (var key in dictionary) {
    // check if the property/key is defined in the object itself, not in parent
    if (dictionary.hasOwnProperty(key)) {
        keys.push(key);
        values.push(dictionary[key]);
    }
}

console.log(`keys: `, keys);
console.log(`values: `, values);
于 2020-06-19T08:27:36.577 回答