javascript在包含object的数组中查找匹配值

时间:2015-08-17 14:12:15

标签: javascript

有两个变量nj和ink。请帮助在数组中找到类似的值

var nj=[{"tf":"1111","tt":"10000","lsp":"27","hsp":"40"}]
var ink=[{"tf":"1111","tt":"10000","lsp":"27","hsp":"40"},{"tf":"2000","tt":"2900","lsp":"127","hsp":"192"}]
答案应该是

[{"tf":"1111","tt":"10000","lsp":"27","hsp":"40"}]

我是javascript的新手,我想在数组中获取相同的对象 和console.log结果

请检查plunker http://plnkr.co/edit/MmNUYDVCw7LzI951DWli?p=preview

中的script.js

1 个答案:

答案 0 :(得分:1)

它做了它应该做的事情并在任何地方循环,并找到结果,我们应该期待什么呢?



function getCommon(a, b) {
    // to start with return, it is always a good idea to do so. it means, i am
    // willing to accomplish something and gives a little hint of what to do.
    // so here we go with a reduce, a method of Array, which main function is to
    // iterate over an array (a in this case) and maintain a return value. so
    // basically right for our return.
    // parameter r for the return value and aa, an item of a
    return a.reduce(function (r, aa) {
        // we need keys to access objects properties for aa and later for bb as well
        var aaKeys = Object.keys(aa);
        // now we have to loop over b
        b.forEach(function (bb) {
            // get the keys for accessing bb
            var bbKeys = Object.keys(bb);
            // the main part of all
            // first check if both of the objects have the same property length
            // if not stop run and say good bye
            aaKeys.length === bbKeys.length &&
            // if same length, go on and have a look for the keys of aa
            // to be shure, that all keys are the same and all properties of the objects
            // are equal, we have to take Array.every, which acts as an all quantifier,
            // what means, that every item must meet the requirements.
            // if not stop run and say good bye (you know it already)
            aaKeys.every(function (key) {
                // in this case the key must be included in the key array (aaKeys) and
                // the same property of aa and bb must match. the result is returned
                return ~bbKeys.indexOf(key) && aa[key] === bb[key];
            }) &&
            // now the final part. at this position we know that both objects
            // are equal. we take one and push it to the result array
            r.push(aa);
        });
        // do not forget to return the result, because Array.reduce works with the
        // last return value as first parameter of the callback
        return r;
    // supply an empty array for the common objects to come
    }, []);
}

var a = [{ tf: "1111", tt: "10000", lsp: "27", hsp: "40" }, { tf: "1999", tt: "2900", lsp: "127", hsp: "192" }, { answer: 42 }],
    b = [{ tf: "1111", tt: "10000", lsp: "27", hsp: "40" }, { tf: "2000", tt: "2900", lsp: "127", hsp: "192" }, { answer: 42 }],
    c = getCommon(a, b);

document.write('<pre>' + JSON.stringify(c, 0, 4) + '</pre>');
&#13;
&#13;
&#13;