......但是有了物体。
例如 :
one = {a: false, c: false, e: false};
two = {a: true, b: false, c: false, d:false};
result = somethingJavascriptHas.ObjectAnd(one, two);
console.log(result);
会回来:
{a: false, c: false};
(我对密钥感兴趣,而不是其余部分,所以我放弃了第二个对象的值,而不是第一个在这里。在我的情况下,两个对象的值总是相同的,只是它们的一些条目将丢失或没有。我想要一个最终对象,其中只包含两个对象中存在的键(具有第一个对象键的值)
这可能吗?
为了完整性,OR,XOR和NOT。 (再次假设第一个传递对象的值的优先级)
您可以在其中一个对象键上使用Array#reduce
函数,并检查两个对象的属性是否未定义:
var one = {a: false, c: false, e: false};
var two = {a: true, b: false, c: false, d:false};
var three = Object.keys(one).reduce((acc, curr) => {
if(two[curr] !== undefined){
acc[curr] = one[curr] && two[curr];
}
return acc;
}, {});
console.log(three);
只是遍历你的对象:
var one = {a: false, c: false, e: false};
var two = {a: true, b: false, c: false, d:false};
var res = {}
for (var o in one) {
for (var t in two) {
if (t == o) res[t] = one[t]
}
}
console.log(res)
// Your example:
/*one = {a: false, c: false, e: false};
two = {a: true, b: false, c: false, d:false};
result = somethingJavascriptHas.ObjectAnd(a, b);
console.log(result);
// would return :
{a: false, c: false};*/
// Working code:
const one = {a: false, c: false, e: false};
const two = {a: true, b: false, c: false, d:false};
const oneTwoIntersection = Object.keys(one)
.reduce((currentObj, nextKey) => {
return !two.hasOwnProperty(nextKey) ? currentObj : Object.assign({}, currentObj, {
[nextKey]: one[nextKey]
});
}, {});
console.log(oneTwoIntersection);
因为你说你只想要钥匙,你可以结合Object.keys,Array#filter和Object#hasOwnProperty
const one = {a: false, c: false, e: false};
const two = {a: true, b: false, c: false, d:false};
const intersection = (a, b) =>
Object.keys(a).filter(aKey => b.hasOwnProperty(aKey));
console.log(intersection(one, two));