我有一个JSON对象,如下面的
{
"db": {
"name": "db",
"connector": "memory"
},
"MySql": {
"host": "localhost",
"port": 3306,
"database": "users",
"username": "root",
"password": "",
"name": "MySql",
"connector": "mysql"
},
"postgreDS": {
"host": "localhost",
"port": 1234,
"database": "abc",
"username": "postgres",
"password": "abc",
"name": "postgreDS",
"connector": "postgresql"
}
我需要此对象的以下输出。
{"db", "MySql", "postgreDS"}
我应该如何从JavaScript中的整个JSON对象中提取上述信息。 以及我将如何读取子键和值。
答案 0 :(得分:1)
像这样(其中obj
是你的JSON对象):
var objectProperties = [];
for(var prop in obj){
objectProperties.push(prop);
}
console.log(JSON.stringify(objectProperties)); // ["db", "MySql", "postgreDS"]
答案 1 :(得分:1)
如果您只想获取嵌套对象的键,请使用Object.keys
:
var keys = Object.keys(obj); // [ "db", "MySql", "postgreDS" ]
如果您希望根据指定的键从嵌套对象中获取值,这里将返回一个返回值数组的泛型函数:
function getValueFromKey(obj, key) {
return Object.keys(obj).map(function (el) {
return obj[el][key];
});
}
getValueFromKey(obj, 'name'); // [ "db", "MySql", "postgreDS" ]
getValueFromKey(obj, 'connector'); // [ "memory", "mysql", "postgresql" ]
答案 2 :(得分:0)
尝试FIDDLE,
的javascript
$(function(){
var output = {};
var items = {
"db": {
"name": "db",
"connector": "memory"
},
"MySql": {
"host": "localhost",
"port": 3306,
"database": "users",
"username": "root",
"password": "",
"name": "MySql",
"connector": "mysql"
},
"postgreDS": {
"host": "localhost",
"port": 1234,
"database": "abc",
"username": "postgres",
"password": "abc",
"name": "postgreDS",
"connector": "postgresql"
}};
for(var propertyName in items) {
output.push(propertyName); // output will have the required output
}
console.log(output);
});