我正在尝试从对象中获取标签列表
以下是完整的代码和数据:
$(document).ready(function() {
obj =
{
"category":[
{
"id":"8098",
"tags":{
"411":"something",
"414":"something else"
}
}
]
};
var tagList = [];
for (var index in obj) {
for (var indexSub in obj[index].tags) {
blah = (obj[index].tags[indexSub]);
tagList.push(blah);
}
}
console.log(tagList);
});
这是指向jsFiddle
的链接问题是taglist返回一个空数组。
我该如何解决这个问题?
答案 0 :(得分:0)
此致
for (var index in obj) {
for (var indexSub in obj[index].tags) {
blah = (obj[index].tags[indexSub]);
tagList.push(blah);
}
}
获取tags
category
的新内容
for (var index in obj) {
for (var indexSub in obj[index]) {
blah = (obj[index][indexSub].tags);
tagList.push(blah);
}
}
查看访问属性
的方式的差异
obj =
{
"category": [
{
"id": "8098",
"tags": {
"411": "something",
"414": "something else"
}
}
]
};
var tagList = [];
for (var index in obj) {
for (var indexSub in obj[index]) {
tagList = (obj[index][indexSub].tags);
// tagList.push(blah);
}
}
console.log(tagList);
答案 1 :(得分:0)
你需要迭代这个类别,然后获取标签的键和值,像这样的东西。
var obj =
{
"category":[
{
"id":"8098",
"tags":{
"411":"something",
"414":"something else"
}
}
]};
var tagList = [];
obj.category.forEach( o =>{
for (property in o.tags){
tagList.push(property + ':'+ o.tags[property]);
};
});
console.log(tagList);
答案 2 :(得分:0)
这是您的jsfiddle
obj =
{
"category":[
{
"id":"8098",
"tags":{
"411":"something",
"414":"something else"
}
}
]
};
var tagList = [];
for (key in obj) {
for(subKey in obj[key]){
var myTags=obj[key][subKey].tags;
for(tag in myTags){
tagList.push(tag);
}
}
}
console.log(tagList);
答案 3 :(得分:0)
您可以使用Array#reduce
和Object.keys
与Array#map
进行迭代并获取所有代码。
var obj = { "category": [{ "id": "8098", "tags": { "411": "something", "414": "something else" } }] },
tagList = obj.category.reduce(function (r, a) {
return r.concat(Object.keys(a.tags).map(function (t) { return a.tags[t]; }));
}, []);
console.log(tagList);