Generating JSON of a JS-Object with only some attributes in JSON
I'm generating JSON from a javascr开发者_开发百科ipt object. But I do not need all attributes from the object in the JSON. Is there a way (or a library) to do this? Till now, I overrided the toJSON function and return a new Object with reduced attributes, but its a nasty workaround, isn't it?
JSON.stringify
accepts a second parameter, a "replacer" function, that you may be able to use to exclude certain properties.
var exclude = { 'akey': true };
var obj = { 'akey': 2, 'anotherkey': 3 };
JSON.stringify(obj, function (key, value) {
if(exclude[key]) return undefined;
return value;
});
=> "{'anotherkey':3}"
Funny I just wrote some code to do this (with objects) which you can then serialize the target.
// sorta like $.extend but limits to updating existing properties
// from a template. takes any number of objects to merge.
function mergeObjects(template) {
var obj={};
if (arguments) {
for (var i = 0; i < arguments.length; i++) {
newObj = arguments[i];
for (var prop in template) {
if (newObj.hasOwnProperty(prop)) {
obj[prop] = newObj[prop];
}
}
}
}
return obj;
}
The way to use this function is with a template object that has the properties you need, e.g.
var template = {
firstname: '',
lastname: ''
}
var someObject = {
firstname: "bryce",
lastname: "nesbitt",
title: "ubergeek"
}
var filteredObject = mergeObjects(template,someObject);
-->
filteredObject: {
firstname: "bryce",
lastname: "nesbitt",
}
http://jsfiddle.net/AARMW/
精彩评论