如何循环遍历对象数组并使用linq.js将属性与变量匹配

时间:2015-05-20 18:46:44

标签: javascript arrays json linq.js

我正在尝试使用linq.js来匹配属性定位对象。我需要匹配的属性是在数组的对象中,然后嵌套在数组数组中。

Json我正在循环

customSeries = [{"name":"Chantal Hamlet - Green Castle Homes","subId":"10223","bldId":"13551","data":[[179900,1386],[214900,1440],[194500,1496],[217900,1504],[189900,1542],[184900,1546],[192500,1570],[189900,1576],[191900,1598],[204900,1626],[219900,1651],[212900,1704],[214900,1787],[219900,1837],[224900,1857]],"removeByNames":[["null"],["null"],["null"],["null"],["null"],["null"],["null"],["null"],["null"],["null"],["null"],["null"],["null"],["null"],["null"]]},{"name":"Ella Sea Condos - Sahnow Construction","subId":"9761","bldId":"27380","data":[[199900,1500]],"removeByNames":[["null"]]},{"style":"smooth","color":"blue","data":[[20000,200],[40000,400],[[40000,400]],[30000,300],[[30000,300]]],"name":"Subject Property","removeByNames":[["Product1"],["Product2"],["Product3"]]}]

要匹配的项目

var modelName = 'Product2'

的javascript

  remove: function (e) {
            removeByNames = []
            var modelName = e.model.name;

            // Enumerate through the series
            var customSeriesSearchResults = Enumerable.From(customSeries)
                .Where(function (item) {
                    // Enumerate through the series.removeByNames
                    return Enumerable.From(item.removeByNames).Any(function (modelName) {

                        // Find matching removeByNames.name
                        return Enumerable.From(removeByNames).Contains(modelName);
                })
            })
                .ToArray();

    }

1 个答案:

答案 0 :(得分:1)

使用纯js,您可以循环遍历每个对象,然后在removedByNames数组上执行另一个循环。 然后在展平的数组上使用array.indexOf(),如果找到,它将返回数组中字符串的位置。如果找不到任何内容,则返回-1。

您可以对linqJs使用相同的方法。不确定在linqjs中是否有更好的方法。但它也适用于linq。

请在jsfiddle查看下面的演示代码。 (我已经向你的json添加了虚拟数据以使第二个对象具有相同的modelName。)



customSeries = [{
    "name": "Chantal Hamlet - Green Castle Homes",
        "subId": "10223",
        "bldId": "13551",
        "data": [
        [179900, 1386],
        [214900, 1440],
        [194500, 1496],
        [217900, 1504],
        [189900, 1542],
        [184900, 1546],
        [192500, 1570],
        [189900, 1576],
        [191900, 1598],
        [204900, 1626],
        [219900, 1651],
        [212900, 1704],
        [214900, 1787],
        [219900, 1837],
        [224900, 1857]
    ],
        "removeByNames": [
        ["null"],
        ["null"],
        ["null"],
        ["null"],
        ["null"],
        ["null"],
        ["null"],
        ["null"],
        ["null"],
        ["null"],
        ["null"],
        ["null"],
        ["null"],
        ["null"],
        ["null"]
    ]
}, {
    "name": "Ella Sea Condos - Sahnow Construction",
        "subId": "9761",
        "bldId": "27380",
        "data": [
        [199900, 1500]
    ],
        "removeByNames": [
        ["null"]
    ]
}, {
    "style": "smooth",
        "color": "blue",
        "data": [
        [30000, 500],
        [40000, 400],
        [
            [40000, 400]
        ],
        [50000, 800],
        [
            [50000, 800]
        ]
    ],
        "name": "Subject Property",
        "removeByNames": [
        ["Product1"],
        ["Product2"],
        [
            ["Product2"]
        ],
        ["Product3"],
        [
            ["Product3"]
        ]
    ]
}, { // add another item with product2
    "style": "smooth",
        "color": "gray",
        "data": [
        [30000, 500],
        [40000, 400],
        [
            [40000, 400]
        ],
        [50000, 800],
        [
            [50000, 800]
        ]
    ],
        "name": "Subject Property dummy data",
        "removeByNames": [
        [
            ["Product2"]
        ],
        ["Product3"],
        [
            ["Product3"]
        ]
    ]
}];


console.log(customSeries);

/*customersWithProduct2 = customSeries.filter(function(customer){ 
    console.log('Cust', customer);
    return customer.modelname === 'Product2';})*/
var modelName = 'Product2'
var customers = [];


// flatten code from here http://stackoverflow.com/questions/6032878/is-there-an-easy-way-to-make-nested-array-flat
var flatten = function (arr) {
    return arr.reduce(function (prev, cur) {
        var more = [].concat(cur).some(Array.isArray);
        return prev.concat(more ? flatten(cur) : cur);
    }, []);
};

//console.log('flat test', flatten(['dummy', ['1','2'], 'dummy2']));
//console.log('flat test', flatten([['1']]));

// with-out linqjs
customSeries.forEach(function (obj) {
    //console.log(obj);
    var foundItem, flattened;

    obj.removeByNames.some(function (name) {
        flattened = flatten(name);

        //console.log('name', name, flattened, flattened.indexOf(modelName) > -1, obj);
        foundItem = flattened.indexOf(modelName) > -1 ? obj : undefined;
        return !!foundItem; //!! creates bool if true exits the loop
    });

    //console.log('found', foundItem);
    if (foundItem) {
        customers.push(foundItem);
    }
});

console.log('pure js', customers);

$('body').append($('<pre/>').html(JSON.stringify(customers, null, 2))); // jquery just to log the object to the output
               
// with linqjs
removeByNames = []
var flatArray = [];

// Enumerate through the series
var customSeriesSearchResults = Enumerable.From(customSeries)
    .Where(function (item) {
    // Enumerate through the series.removeByNames
    return Enumerable.From(item.removeByNames).Any(function (name) {

        // Find matching removeByNames.name
        // console.log('loop', Enumerable.From(item.removeByNames)
        // ,Enumerable.From(removeByNames).Contains(modelName));
        flatArray = flatten(Enumerable.From(item.removeByNames).ToArray());
        return flatArray.indexOf(modelName) > -1; //Enumerable.From(flatArray).Contains(modelName);
    })
}).ToArray();

console.log('with linqjs', customSeriesSearchResults);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>
&#13;
&#13;
&#13;