具有重复名称的JS关联对象 [英] JS associative object with duplicate names

查看:117
本文介绍了具有重复名称的JS关联对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我有一个像这样的对象:

ok, so I have an object like:

var myobject = {
   "field_1": "lorem ipsum",
   "field_2": 1,
   "field_2": 2,
   "field_2": 6
};

如您所见,对象中有重复的名称,但值不同。如果我像(使用jQuery)那样经历它:

as you see there are duplicate names in the object, but with different values. If i go through it like (using jQuery):

$.each(myobject, function(key, value)
{
   console.log(key);
   console.log(myobject[key]);
   console.log(myobject[value]);
}

key - returns the correct key
myobject[key] - returns the name for that key
myobject[value] - returns the last elements', with that name, value

对于field_2,它将返回6,但它会打印3次,因为它在对象中重复3次。

meaning for field_2 it will return 6, though it'll print it 3 times, as it repeats 3 times in the object.

我的问题是如何获得重复命名字段的正确值,而不仅仅是最后一个

My question is how to obtain the correct value for that duplicate named fields and not just the last one's

谢谢

推荐答案

这不是一个对象的数组。你最好创建一个对象的属性一个数组并存储不同的值。

That is not an array that is an object. You'd be better creating a property of the object that is an array and store the different values in there.

var myarray = {
   "field_1": "lorem ipsum",
   "field_array": []
};

myarray.field_array.push(value);

然后循环遍历该数组的属性。

then just loop through that property of the array.

这篇关于具有重复名称的JS关联对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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