JS JSON 对键 &价值
这是从 JS 对象获取键和值的最佳方法吗:
function jkey(p){for(var k in p){return k;}}
function jval(p){for(var k in p){return p[k];}}
var myobj = {'Name':'Jack'};
alert(jkey(myobj)+' equals '+jval(myobj));
还是有更直接或更快速的方法?
我需要做的是能够分别调用键名和值。这些函数可以工作并返回键名和值,我只是想知道是否有更小、更快、更好的方法。
这是一个更好的例子,我想将 key:value 作为单独的变量访问,即 {assistant:'XLH'}, key=assistant, val = 'XLH';
我仅在确定它是一对并且仅返回单个键和值时才使用它。
formY={
tab:[
{
tabID:'Main',
fset:[
{
fsID:'Ec',
fields:[
{ec_id:'2011-03-002'},
{owner:'ECTEST'},
{assistant:'XLH'},
{ec_date:'14/03/2011'},
{ec_status:'Unreleased'},
{approval_person:'XYZ'},
]
}
]
}
]
}
Is this the best way to get the key and value from a JS object:
function jkey(p){for(var k in p){return k;}}
function jval(p){for(var k in p){return p[k];}}
var myobj = {'Name':'Jack'};
alert(jkey(myobj)+' equals '+jval(myobj));
Or is there a more direct or faster way ??
What I need to do is to me able to call the key-name and value seperately. the functions work and return the keyname and value, I just wondered if there was a smaller, faster, better way.
Here's a better example, I want to access the key:value as separate variables i.e {assistant:'XLH'}, key=assistant, val = 'XLH';
I only use this when I know for sure that it is a pair and only returns a single key and value.
formY={
tab:[
{
tabID:'Main',
fset:[
{
fsID:'Ec',
fields:[
{ec_id:'2011-03-002'},
{owner:'ECTEST'},
{assistant:'XLH'},
{ec_date:'14/03/2011'},
{ec_status:'Unreleased'},
{approval_person:'XYZ'},
]
}
]
}
]
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最好避免循环对象两次。你可以这样做:
并用以下方式调用它:
It would be better to avoid looping the object twice. You could do this:
and call it with:
为了在一行代码中设置 JSON 对象,我喜欢使用 jQuery 的 parseJSON 方法。只需传入您的 JSON 字符串,它就会为您创建对象。然后您所要做的就是使用 obj.Property 来访问任何值。
For setting an object from JSON in a single line of code I like using the jQuery's parseJSON method. Just pass in your JSON string and it creates the object for you. Then all you have to do is use your obj.Property to access any value.
我发现你的问题有点不清楚,但我怀疑你正在寻找:
I'm finding your question is a little unclear, but I suspect you are looking for: