Finding The Intersection Of Properties In Javascript Objects
Hi guys suppose I have following two objects var obj1 = {one:232,two:3123,three:3232} var obj2 = {one:323,three:3444,seven:32} I am trying write a function that will return the pr
Solution 1:
Make it easy on yourself-
Object.keys returns an array, you can use array filter.
var commonproperties= function(o1, o2){
return Object.keys(o1).filter(function(itm){
return itm in o2
});
}
var obj1 = {one:232,two:3123,three:3232},
obj2 = {one:323,three:3444,seven:32};
commonproperties(obj1 ,obj2);
/* returned value: (Array)
['one','three']
*/
Solution 2:
I made my own since I don't find the one I need. One line intersection
x={x:1, y:2, z:1};
y={x:3, z:4, r:5};
intersect = Object.keys(x).filter(c => Object.keys(y).indexOf(c) !== -1).reduce((a,b) => {let b1={}; b1[b]=x[b]; return {...a, ...b1}}, {});
console.log(intersect);
Post a Comment for "Finding The Intersection Of Properties In Javascript Objects"