Javascript 如何循环对象并测试它是否';这是唯一的钥匙

Javascript 如何循环对象并测试它是否';这是唯一的钥匙,javascript,jquery,json,Javascript,Jquery,Json,我正在使用jQuery.serializeJSON()。基本上,我有这样一种形式: <input name='store[products][][type]' type='text' value='TableSaw' /> <textarea name='store[products][][description]'></textarea> <textarea name='store[products][][price]'></textare

我正在使用jQuery.serializeJSON()。基本上,我有这样一种形式:

<input name='store[products][][type]' type='text' value='TableSaw' />
<textarea name='store[products][][description]'></textarea>
<textarea name='store[products][][price]'></textarea>
用户可以更改/删除/描述、价格和其他属性。基本上,我想做的是测试type是否是唯一存在的键

现在看来:

{"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.
如果只设置了类型,而没有其他设置。

请尝试以下操作:

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);
}

for(var i=0;i您可以在将json定义分配给这样的对象时执行此操作

var data = {"store":{"products":[{"type":"TableSaw","description":"Really cool saw, should buy it ","price": "20.99"}]}};
您只需测试
描述
价格
元素的类型,如果它们不存在,则将数组
产品
设置为空,如下所示:

if( typeof(data.store.products[0].desctiption) == 'undefined' || typeof(data.store.products[0].price) == 'undefined')
    data.store.products = [];

有一种神奇的方法可以做到这一点。你需要一个简单的
if
语句。你已经给了我们它的伪代码,所以只需在实际代码中实现它。你在后端使用什么?或者你可以在使用时使用if语句ajax@meagar,我想我没有把我的问题说清楚。如果我只是想做点什么看看就好了如果
description&&price
为空,但我有动态键(例如,像我在问题中提到的颜色和大小)。如果只设置了类型,而所有其他键/值都为空,有没有办法删除?那么,您只是在问如何获取对象的键,这样您就可以测试
type
是否是唯一存在的键。请查看副本。@meager,谢谢您的参考,但这个问题真的算是副本吗?我不是在问“如何获取对象的键”,我在问“如何循环对象并测试它是否是唯一存在的键”“。我编辑标题是为了让这个问题变得更好。谢谢你的回答。我对我的问题真的不太清楚,我现在编辑得更清楚。基本上,我正在尝试测试type是否是对象中设置的唯一键/值,如果是,则删除整个对象。”。