检查对象是否存在,并且在嵌套对象(对象数组)中将属性设置为特定值

时间:2014-11-04 14:40:48

标签: javascript jquery

我试图从数据源构造一个JSON对象,它看起来像这样:

var allProduce = [
        {"name": "cabbage", "type": "vegetable"},
        {"name": "potoato", "type": "vegetable"},
        {"name": "carrot", "type": "vegetable"},
        {"name": "apple", "type": "fruit"},
        {"name": "orange", "type": "fruit"}
]

当我处理数据源时,我想添加到嵌套对象' allProduce' 一个新对象,其中包含相应的条目当且仅当对象不存在。

因此,如果我的数据源中包含以下行:

**Product          Type     Country origin      In stock?**
apple            fruit       Ireland             Yes
apple            fruit       France              Yes
apple            fruit       USA                 No
cabbage          vegetable   UK                  Yes
cabbage          vegetable   France              No

然后由此产生的所有产品'嵌套对象应该是:

var allProduce = [
        {"name": "apple", "type": "fruit"},
        {"name": "cabbage", "type": "vegetable"}
 ]

这是我感到困惑的地方,因为我不确定每次检查(没有遍历整个嵌套对象?),无论记录是否存在。我正在做这样的事情(使用jQuery:

 $('.sourceData table tbody tr').each(function(i,row) {
    var fruitName = $.trim($(row).find('td:nth-child(1)').text()); 
    var type = $.trim($(row).find('td:nth-child(2)').text()); 

    if (AN OBJECT WITH THE "NAME" PROPERTY SET TO fruitName DOESN'T ALREADY EXIST) {
       allProduce.push({"name":fruitName, "type": type});

    }
 });

if语句的括号内应该是什么,我当前有(对象是" NAME"属性设置为fruitName DOESN' T ALREADY EXIST) 。或者有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

您可以将对象用作HashSet,以查看是否遇到某个名称。以下示例:

(function () {
    var exists = {};
    $('.sourceData table tbody tr').each(function (i, row) {
        var fruitName = $.trim($(row).find('td:nth-child(1)').text());
        var type = $.trim($(row).find('td:nth-child(2)').text());

        //AN OBJECT WITH THE "NAME" PROPERTY SET TO fruitName DOESN'T ALREADY EXIST
        if (!exists[fruitName]) {
            exists[fruitName] = true;
            allProduce.push({"name": fruitName, "type": type});

        }
    });
})();

答案 1 :(得分:1)

您可以使用JQuery的filter()方法:

$('.sourceData table tbody tr').each(function(i,row) {
    var fruitName = $.trim($(row).find('td:nth-child(1)').text()); 
    var type = $.trim($(row).find('td:nth-child(2)').text());

    if ($(allProduce).filter(function(index, object){return object.name == fruitName;}).length == 0) {
       allProduce.push({"name":fruitName, "type": type});

    }
 });