Javascript 访问名称/值对
我得到的 JSON 名称/值对如下所示:
{
"Name":"parentid",
"Value":"blah"
},
{
"Name":"siteid",
"Value":"blah"
},
{
"Name":"sitename",
"Value":"blah"
}
但我想访问“名称”值作为 KEY,将“值”值作为 VALUE 访问。有没有一种优雅的方法可以将那段 JSON 变成这样的东西?
{'parentid', 'blah'},
{'sitename', 'blah'}
I'm getting JSON name/value pairs that looks like this:
{
"Name":"parentid",
"Value":"blah"
},
{
"Name":"siteid",
"Value":"blah"
},
{
"Name":"sitename",
"Value":"blah"
}
But I would like to access the "name" value as the KEY, and the "value" value as the VALUE. Is there an elegant way to turn that piece of JSON into something like this?
{'parentid', 'blah'},
{'sitename', 'blah'}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
试试这个:
这将导致类似的结果:
Try this:
This will result in something like:
一种方法可以做到这一点。
One way to do it.
这是一个函数,它将采用您所呈现的形式的对象,并将其输出为“普通”对象,其中名称值作为键,值作为值。
This is a function that will take an object in the form you presented, and output it as a "normal" object with the name values as keys, and the value values as values.
我建议使用
for( ... in ... )
方法来完成此任务。它会根据您的需要获取关键名称。你最终得到(来自 Firebug)
Object Name=parentid Value=blah
,可以通过 object.key 或 object[ 'key' ] 访问(在我们的例子中是 assoc.Name 或 assoc[ 'Value '])
这是来自雅虎的道格拉斯·克罗克福德(Douglas Crockford)的链接!关于使用它 - http://yuiblog.com/blog /2006/09/26/为了阴谋/
I'd recommend using the
for( ... in ... )
method for this task. It'll grab the key names like you need.and you end up with (from Firebug)
Object Name=parentid Value=blah
that can be accessed by object.key or object[ 'key' ] (in our case assoc.Name or assoc[ 'Value' ])
here's a link from Douglas Crockford from Yahoo! about using it as well - http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
我假设你正在使用 PHP,并且 PHP 会像这样回应你的关联:
在你的 javascript 中,你可以这样做:
我不确定这是否是你想要的,但它是一个解决方案。
I'm assuming you are using PHP, and the PHP echoes you assosiatice aray like this:
In your javascript, you could do this:
I'm not sure if this is what you want, but it's a solution.