Skip to content

Instantly share code, notes, and snippets.

@jiahuang
Created April 20, 2012 05:06
Show Gist options
  • Save jiahuang/2426150 to your computer and use it in GitHub Desktop.
Save jiahuang/2426150 to your computer and use it in GitHub Desktop.
javascript trying to stringify map results
/*
Let's say I have this html
<table id="switchesTbl">
<tr>
<td><div class="addButton" type="switch"></div></td>
<td><div class="createLabel">Switch</div></td>
<td><input type="text" class="createInput" value="s1"/></td>
<td><div class="createLabel">Description</div></td>
<td><input type="text" class="createInput" value="d1"/></td>
<td><div class="createLabel">Default</div></td>
<td><input type="text" class="createInput" value="def1"/></td>
</tr>
<tr>
<td><div class="addButton" type="switch"></div></td>
<td><div class="createLabel">Switch</div></td>
<td><input type="text" class="createInput" value="s2"/></td>
<td><div class="createLabel">Description</div></td>
<td><input type="text" class="createInput" value="d2"/></td>
<td><div class="createLabel">Default</div></td>
<td><input type="text" class="createInput" value="def2"/></td>
</tr>
</table>
And my ideal output is something like this
[{switch:s1, description:d1, default:def1}, {switch:s2, description:d2, default:def2}]
*/
// if I try to map it
var switchesObj = $('#switchesTbl tr').map(function(){
var inputs = $(this).find(':input');
return {switch:$(inputs[0]).val(), description:$(inputs[1]).val(), default:$(inputs[2]).val()}
});
console.log(switchesObj);
// // This breaks
console.log(JSON.stringify(switchesObj));
// trying to fix stringify by not converting __proto__ to string
console.log(JSON.stringify(switchesObj, function (key, value) {
if (typeof value == 'Object') { // key == '__proto__' also doesn't filter it out
return '';
}
return value;
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment