jCard to Object
Converts jCards to proper Javascript Objects
by jwerre
JavaScript
var jcard = ["vcard", [
["version", {}, "text", "4.0"],
["n", {}, "text", ["Gump", "Forrest", "", "Mr.", ""]],
["fn", {}, "text", "Forrest Gump"],
["org", {}, "text", "Bubba Gump Shrimp Co."],
["title", {}, "text", "Shrimp Man"],
["photo", {
"mediatype": "image/gif"
}, "uri", "http://www.example.com/dir_photos/my_photo.gif"],
["tel", {
"type": ["work", "voice"]
}, "uri", "tel:+1-111-555-1212"],
["tel", {
"type": ["home", "voice"]
}, "uri", "tel:+1-404-555-1212"],
["adr", {
"label": "100 Waters Edge\nBaytown, LA 30314\nUnited States of America",
"type": "work",
"pref": "1"
},
"text", ["", "", "100 Waters Edge", "Baytown", "LA", "30314", "United States of America"]
],
["adr", {
"label": "42 Plantation St.\nBaytown, LA 30314\nUnited States of America",
"type": "home"
},
"text", ["", "", "42 Plantation St.", "Baytown", "LA", "30314", "United States of America"]
],
["email", {}, "text", "[email protected]"],
["rev", {}, "timestamp", "2008-04-24T19:52:43Z"]
]]
function parsejCard(card) {
var obj = {},
getVals = function (item) {
return {
params: item[1],
type: item[2],
values: item[3]
};
}
card[1].forEach(function(item, index) {
if (obj.hasOwnProperty(item[0])) {
obj[item[0]] = val = [obj[item[0]]];
val.push(getVals(item));
} else {
obj[item[0]] = getVals(item)
}
});
return obj;
}
console.log( parsejCard(jcard) );