如何循环遍历一个对象并测试它是否为唯一存在的键

how to loop through an object and test for if it's the only key present

本文关键字:是否 唯一 存在 测试 何循环 循环 一个对象 遍历      更新时间:2023-09-26

我正在使用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"}]}}

用户可以修改/删除/描述、价格等属性。基本上,我要做的是测试type是否是唯一存在的键。

现在它看起来像:

{"store":{"products":[{"type":"TableSaw"}]}} //JUST TYPE IS SENT TO DB. NOT WHAT I WANT

但是我想要达到的是:

{"store":{"products":[]}} //WHAT I WANT TO SEND TO DB.

try this:

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

当您将json定义分配给一个对象时,可以这样做

var data = {"store":{"products":[{"type":"TableSaw","description":"Really cool saw, should buy it ","price": "20.99"}]}};

所有你需要做的是测试descriptionprice元素的类型,如果它们不存在,你使数组products为空,像这样:

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