读取并循环遍历具有非唯一键值对的对象 [英] Read and loop through an object with non-unique key value pairs

查看:46
本文介绍了读取并循环遍历具有非唯一键值对的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些键/值对的对象.当有一个键/值对与另一个键/值对共享相同的键时,我在控制台记录对象时无法识别第一个.

I have an object which contains some key/value pairs. When there is a key/value pair that shares the same key as another key/value pair, the first one is not recognised when I console log the object.

例如:

var test = {
"same" : 'Value1',
"same" : 'Value2',
"different" : 'Value3'
};
console.log(test);

在控制台中的结果为:

Object { same="Value2", different="Value3"}

是否无法读取具有相似键名的对象?

Is it not possible to read an object that has similar key names?

我正在尝试使用此方法遍历对象 (如何遍历或枚举 JavaScript对象?)但我只能检索一个共享一个键的键/值对.

I am trying to loop through the object using this method (How do I loop through or enumerate a JavaScript object?) but I can only ever retrieve one the key/value pairs that share a key.

推荐答案

如果需要,您可以更改 JSON 的结构吗?JSON 对象不能有重复的键.把它想象成一个哈希图或字典.根据语言和 JSON 解析器的不同,您也可能会遇到异常(尽管不是在 Javascript 中)

Could you change the structure of the JSON if needed? JSON objects cannot have duplicate keys. Think of it as a hashmap or dictionary. Depending on the language and JSON parser you may also get an exception (not in Javascript though)

在上面的示例中,要么更改它,以便您拥有唯一键,要么将 ti 更改为一组值,例如:

In your example above either change it so that you have unique keys or change ti to an array of values like:

var test = {
"same" : ['Value1', 'Value2']
"different" : 'Value3'
};
console.log(test);

这篇关于读取并循环遍历具有非唯一键值对的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆