我有以下json:
var testjson = {
"Mytest": [{
"Testing": {
"static": {
"name": "first name"
},
"key1": "key1 val",
"key2": 10
}
}, {
"Testing": {
"static": {
"name": "second name"
},
"key3": 20,
"key4": true
}
}, {
"Testing": {
"static": {
"name": "third name"
},
"key5": "key5 val"
}
}]
}
我有以下coffeescript:@ itemNames = (item for item of @mydata).sort (a,b) -> a>b
,但我将其更改为以下javascript转换:
var mydata = testjson.Mytest;
var item;
this.itemNames = ((function() {
var results;
results = [];
for (item in mydata) {
results.push(item);
}
return results;
}).call(this)).sort(function(a, b) {
return a > b;
});
console.log(mydata);//gives: [Object, Object, Object]
console.log(this.itemNames);//gives: ["0", "1", "2"], but I need it like: ["first name", "second name", "third name"], how can I get it ?
这里我在控制台中输出:["0", "1", "2"]
,但我需要它:["first name", "second name", "third name"]
,当然如果我在控制台上展开它,它应该显示这些值(如:0: "first name", 1: "second name", 2: "third name"
)。创建Fiddle。
请帮助我知道如何获得这些名字并提前致谢。
答案 0 :(得分:1)
你可以这样做。你的项目是元素的索引。你需要在索引处获取元素,然后通过name
访问属性Testing.static.name
。
this.itemNames = ((function() {
var results;
results = [];
for (item in mydata) {
results.push(mydata[item].Testing.static.name);
}
return results;
}).call(this)).sort(function(a, b) {
return a > b;
});
这是代码。
var testjson = {
"Mytest": [{
"Testing": {
"static": {
"name": "first name"
},
"key1": "key1 val",
"key2": 10
}
}, {
"Testing": {
"static": {
"name": "second name"
},
"key3": 20,
"key4": true
}
}, {
"Testing": {
"static": {
"name": "third name"
},
"key5": "key5 val"
}
}]
};
var mydata = testjson.Mytest;
var item;
this.itemNames = ((function() {
var results;
results = [];
for (item in mydata) {
results.push(mydata[item].Testing.static.name);
}
return results;
}).call(this)).sort(function(a, b) {
return a > b;
});
console.log(this.itemNames);

答案 1 :(得分:0)
您可以使用这个简单的解决方案......
var mydata = testJSON.Mytest;
var nameArray = [];
var nameMap= {};
var count =0;
$.each(mydata , function(i , data)
{
var data1 = data.Testing
var name = data1.static.name
nameArray.push(name);
nameMap[count] = name;
count ++;
});
console.log(nameArray);
console.log(nameMap);