我有几个对象:
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"]
要比较的参数/对象的数量可能会有所不同,所以我不确定如何处理。有什么想法吗?
答案 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);

您可以从所有对象和
中获取密钥
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)