Ale*_*lex 1 javascript properties object
我有几个对象:
var a = { "abc": {}, "def": {}, "ghi": {} };
var b = { "abc": {}, "ghi": {}, "jkl": {}, "mno": {} };
var c = { "abc": {}, "ghi": {}, "xyz": {}, "mno": {} };
Run Code Online (Sandbox Code Playgroud)
我想知道如何获取所有属性中存在的属性名称:
var d = getOmniPresentProperties(a, b, c);
function getOmniPresentProperties() {
// black magic?
}
Run Code Online (Sandbox Code Playgroud)
所以d应该是["abc", "ghi"]
要比较的参数/对象的数量可能会有所不同,所以我不确定如何处理.有任何想法吗?
使用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);Run Code Online (Sandbox Code Playgroud)
您可以从所有对象中获取密钥
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)Run Code Online (Sandbox Code Playgroud)