Sasi Dunston
Sasi Dunston

Reputation: 724

Get key along with an value from list of objects in javascript

How can I get key & value object from a list of objects?

For instance:

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

    "key2" {
        "firstName": "Test",
        "middleName": "",
        "lastName": "",
        "login": "[email protected]",
        "photoID": ""
    },

    "key3" {
        "firstName": "First",
        "middleName": "",
        "lastName": "User",
        "login": "[email protected]",
        "photoID": ""
    }
}

where if i query for a particular key for example "key1" i expect the output have to be {"key1":{"firstName":"","middleName":"","lastName":"","login":"","photoID":""}.

Upvotes: 0

Views: 40

Answers (2)

TheFrenchieCake
TheFrenchieCake

Reputation: 123

You can do it slighty lighter: 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)

Upvotes: 2

kiran
kiran

Reputation: 384

This should work, You are creating a new object with the key and value

function getKeyObj(key){
   var returnObj;
   if(!key){ 
     return returnObj;
   }
   var value = globalObjJSON[key];

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

  return returnObj;

}

Upvotes: 2

Related Questions