从javascript中的对象列表中获取键和值

时间:2015-07-10 17:06:25

标签: javascript

我如何获得关键&来自对象列表的值对象?

例如:

var globalObjJSON = {
    "key1": {
        "firstName": "",
        "middleName": "",
        "lastName": "",
        "login": "",
        "photoID": ""
    },

    "key2" {
        "firstName": "Test",
        "middleName": "",
        "lastName": "",
        "login": "testthis@test.com",
        "photoID": ""
    },

    "key3" {
        "firstName": "First",
        "middleName": "",
        "lastName": "User",
        "login": "email@contactmethod.com",
        "photoID": ""
    }
}

如果我查询特定键,例如“key1” 我希望输出必须是 {"key1":{"firstName":"","middleName":"","lastName":"","login":"","photoID":""}

2 个答案:

答案 0 :(得分:2)

这应该可行,您正在使用键和值

创建一个新对象
function getKeyObj(key){
   var returnObj;
   if(!key){ 
     return returnObj;
   }
   var value = globalObjJSON[key];

   if(value) {
     returnObj = {};
     returnObj[key] = value
   }

  return returnObj;

}

答案 1 :(得分:2)

你可以做得轻一些: http://jsfiddle.net/95fvqrfL/3/

var getObjectFromJSON = function(key, jsonObj){
    if(jsonObj[key]){
        var obj = { key: jsonObj[key]};
        obj = JSON.stringify(obj).replace('key', key);
        return JSON.parse(obj);
    }
};

(适用EDITED)