【问题标题】:how to loop through an object and test for if it's the only key present [duplicate]如何遍历一个对象并测试它是否是唯一存在的键[重复]
【发布时间】:2014-09-19 00:18:29
【问题描述】:

我正在使用 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.

如果只设置了类型,没有别的。

【问题讨论】:

  • 有一种神奇的方法可以做到这一点。您需要一个简单的if 语句。你已经给了我们它的伪代码,所以只需在实际代码中实现它。
  • 你在后端使用什么??或者你可以使用 if 语句以防你使用 ajax
  • @meagar,我想我的问题还不够清楚。如果我只是要做一些事情来查看description &amp;&amp; price 是否为空,那会很简单,但我有动态键(例如,像我在问题中提到的颜色和大小)。如果设置了 ONLY 类型,并且所有其他键/值都为空,有没有办法删除?
  • 然后,您只是在询问如何获取对象的键,因此您可以测试 type 是否是唯一存在的键。查看副本。
  • @meager,感谢您的参考,但是这个问题真的算作重复吗?我不是在问“如何获取对象的键”,而是在问“如何遍历对象并测试它是否是唯一存在的键”。我编辑了标题以使这个问题更好。

标签: javascript jquery json


【解决方案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);
}

【讨论】:

    【解决方案2】:

    您可以在将 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 = [];
    

    【讨论】:

    • 感谢您的回答。我真的不清楚我的问题,我现在已经编辑得更清楚了。基本上,我正在尝试测试 type 是否是对象中设置的唯一键/值,如果是,则删除整个对象。
    猜你喜欢
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 2019-01-26
    • 1970-01-01
    相关资源
    最近更新 更多