使用 jQuery 获取 JSON 中键/值对中的键名称?
假设我有这个 JSON:
[
{
"ID": "1",
"title": "Title 1",
},
{
"ID": "2",
"title": "Title 2",
}
]
我将如何返回每条记录重复出现的键名称集?在本例中,为ID,标题
。
我尝试过:
$.getJSON('testing.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(key +', ');
});
$('<p/>', {
html: items.join('')
}).appendTo('#content');
});
没有成功。
这是一个 JSON“数据库”,每个“记录”都有相同的键。我只想要一个脚本来告诉我键是什么,而不是测试它们是否出现在每个条目中。
Say I have this JSON:
[
{
"ID": "1",
"title": "Title 1",
},
{
"ID": "2",
"title": "Title 2",
}
]
How would I return the set of key names that recur for each record? In this case, ID, title
.
I tried:
$.getJSON('testing.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(key +', ');
});
$('<p/>', {
html: items.join('')
}).appendTo('#content');
});
without success.
This is a JSON "database", and every "record" has the same keys. I just want a script that will tell me what the keys are, not test whether or not they occur in every entry.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这将为您提供一个包含在对象数组中匹配的所有字符串属性的数组。这就是您要找的吗?
This will give you an array of all the string properties that match across an array of objects. Is that what you are looking for?
也许是这样的?
当然,这将返回任何一个对象中存在的项,而不是所有对象中都存在的项。从您的问题中尚不完全清楚这是否是您想要的解决方案。
Something like this, perhaps?
Of course, that will return items that exist in any one of the objects, not that exist in all. It's not entirely clear from your question if this is the solution you want.
这可能可以变得更加高效/简洁,但是下面的函数可以做到这一点。
This can probably be made more efficient/concise, but the function below will do it.