Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 13. Write a method that finds deep intersections of objects
- const obj1 = { a: 1, b: { c: 3 } };
- const obj2 = { b: { c: 3 }, d: 4 };
- function intersectionDeep(obj1, obj2) {
- // {c : 3} {c : 3}
- function isDeepEqual(v1, v2) {
- // return JSON.stringify(v1) === JSON.stringify(v2)
- if (v1 === v2) {
- return true;
- }
- // ocekuvame objects
- if (
- v1 === null ||
- v2 === null ||
- typeof v1 !== "object" ||
- typeof v2 !== "object"
- ) {
- return false;
- }
- let v1k = Object.keys(v1);
- let v2k = Object.keys(v2);
- // ako ima ralizcen broj na props
- if (v1k.length !== v2k.length) {
- return false;
- }
- // c
- for (const prop of v1k) {
- if (!v2k.includes(prop) || !isDeepEqual(v1[prop], v2[prop])) {
- return false;
- }
- }
- return JSON.stringify(value1) === JSON.stringify(value2);
- }
- const output = {};
- const keys1 = Object.keys(obj1);
- const keys2 = Object.keys(obj2);
- // zaednicki elementi od dve nizi
- const intersectionKeys = keys1.filter((key1) => keys2.includes(key1));
- // console.log({ intersectionKeys })["b"];
- for (const prop of intersectionKeys) {
- if (isDeepEqual(keys1[prop], keys2[prop])) {
- output[prop] = keys1[prop];
- }
- }
- console.log({ output });
- return output;
- }
- intersectionDeep(obj1, obj2); // -> {b: {c : 3}}
- const ob1 = { a: 1, b: { c: { d: 5 } } };
- const ob2 = { b: { c: { d: 5 } }, d: 4 };
- function intersectionDeep(ob1, ob2) {
- var newObj = {};
- for (var key in ob1) {
- if (typeof ob1[key] === "object") {
- var obj = intersectionDeep(ob1[key], ob2[key]);
- newObj[key] = obj;
- } else if (ob1[key] === ob2[key]) {
- newObj[key] = ob1[key];
- }
- }
- return newObj;
- }
- function isObject(object) {
- return object != null && typeof object === "object";
- }
- console.log(intersectionDeep(ob1, ob2));
Advertisement
Add Comment
Please, Sign In to add comment