给定一个对象列表,如何只返回所有对象中存在的属性?

时间:2017-02-22 11:40:42

标签: javascript object properties

我有几个对象:

var a = { "abc": {}, "def": {}, "ghi": {} };
var b = { "abc": {}, "ghi": {}, "jkl": {}, "mno": {} };
var c = { "abc": {}, "ghi": {}, "xyz": {}, "mno": {} };

我想知道如何获取所有属性中存在的属性名称:

var d = getOmniPresentProperties(a, b, c);

function getOmniPresentProperties() {
  // black magic?
}

所以d应为["abc", "ghi"]

要比较的参数/对象的数量可能会有所不同,所以我不确定如何处理。有什么想法吗?

1 个答案:

答案 0 :(得分:6)

使用Array#filter方法过滤掉值。



var a = { "abc": {}, "def": {}, "ghi": {} };
var b = { "abc": {}, "ghi": {}, "jkl": {}, "mno": {} };
var c = { "abc": {}, "ghi": {}, "xyz": {}, "mno": {} };

var d = getOmniPresentProperties(a, b, c);


function getOmniPresentProperties(...vars) {
  return Object.keys(vars[0]) // get object properties of first array
    .filter(function(k) { // iterate over the array to filter out
      return vars.every(function(o) { // check the key is ehist in all object
        return k in o;
      })
    })
}

console.log(d);




ES5版本

您可以从所有对象和

中获取密钥



function getOmniPresentProperties(a,b,c) {
  return Object.keys(a).filter(function(key){
    return key in a && key in b && key in c
  })
}

var a = { "abc": {}, "def": {}, "ghi": {} };
var b = { "abc": {}, "ghi": {}, "jkl": {}, "mno": {} };
var c = { "abc": {}, "ghi": {}, "xyz": {}, "mno": {} };

var d = getOmniPresentProperties(a, b, c);
console.log(d)