我正在使用jQuery.serializeJSON(https://github.com/marioizquierdo/jquery.serializeJSON)。基本上,我的表格如下:
<input name='store[products][][type]' type='text' value='TableSaw' />
<textarea name='store[products][][description]'></textarea>
<textarea name='store[products][][price]'></textarea>
序列化后的情况如下:
{"store":{"products":[{"type":"TableSaw","description":"Really cool saw, should buy it ","price": "20.99"}]}}
用户可以更改/删除/描述,价格和其他属性。基本上,我想要做的是测试类型是否是唯一存在的键。
现在看起来像:
{"store":{"products":[{"type":"TableSaw"}]}} //JUST TYPE IS SENT TO DB. NOT WHAT I WANT
但我想要实现的目标是:
{"store":{"products":[]}} //WHAT I WANT TO SEND TO DB.
如果只设置了类型,则没有别的。
答案 0 :(得分:1)
试试这个:
for (var i=0; i<store.products.length;i++) {
if (!isValid(store.products[i])) {
delete store.products[i];
}
}
function isValid(product) {
return (product.type && product.description && product.price);
}
答案 1 :(得分:0)
将json定义分配给像这样的对象
时,可以执行此操作var data = {"store":{"products":[{"type":"TableSaw","description":"Really cool saw, should buy it ","price": "20.99"}]}};
您需要做的就是测试description
和price
元素的类型(如果它们不存在)您将数组products
清空如下:
if( typeof(data.store.products[0].desctiption) == 'undefined' || typeof(data.store.products[0].price) == 'undefined')
data.store.products = [];