【问题标题】:Return object in array if contain key value pairs如果包含键值对,则返回数组中的对象
【发布时间】:2017-07-15 04:48:53
【问题描述】:

如果数组中包含特定的键值对,如何返回对象?

如果它给出了所有键值对,我需要返回它,而不仅仅是一个。

例如,

此函数将对象数组作为第一个参数,并将具有给定键值对的对象作为第二个参数

whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 }); 

应该返回

[{ "a": 1, "b": 2 }, { "a": 1, "b": 2, "c": 2 }]

【问题讨论】:

标签: javascript arrays loops object properties


【解决方案1】:

您可以使用filter()every() 来做到这一点。

function whatIsInAName(a, b) {
  return a.filter(function(e) {
    return Object.keys(b).every(function(c) {
      return e[c] == b[c]
    })
  })
}

console.log(whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })) 

【讨论】:

  • 感谢您的帮助!欣赏它!
【解决方案2】:

使用 underscore.js。很简单。

function whatIsInAName(a, b){
	return _.where(a, b);
}
var data = whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 });

console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

【讨论】:

    【解决方案3】:

    Array#filter 方法与Array#every 方法一起使用。

    function whatIsInAName(arr, obj) {
      // get the keys array
      var keys = Object.keys(obj);
      // iterate over the array
      return arr.filter(function(o) {
        // iterate over the key array and check every property
        // is present in the object with the same value 
        return keys.every(function(k) {
          return obj[k] === o[k];
        })
      })
    }
    
    
    console.log(whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 }));

    【讨论】:

    • 谢谢!感谢您的帮助!
    【解决方案4】:

    您可以通过检查模式的键和值来过滤数组。

    function whatIsInAName(array, pattern) {
        var keys = Object.keys(pattern);
        return array.filter(function (o) {
            return keys.every(function (k) {
                return pattern[k] === o[k];
            });
        });
    }
    
    console.log(whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 }));

    【讨论】:

    • pattern[k] = o[k] 这是一个分配,没有比较;) 我会从循环中删除/提取这部分Object.keys(pattern)
    猜你喜欢
    • 2019-04-29
    • 2020-11-13
    • 1970-01-01
    • 2020-12-08
    • 2018-06-14
    • 1970-01-01
    • 2021-03-23
    • 2021-08-26
    • 2020-07-19
    相关资源
    最近更新 更多