Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การแสดงรายการค่าซ้ำทั้งหมดใน Nested JavaScript Object

สมมติเรามี nested object ที่มีข้อมูลสัตว์เลี้ยงแบบนี้:

const pets = {
  owner1: 'Frank',
  owner2: 'Curly',
  owner3: 'Maurice',
  dogs: {
    terriers: {
      name1: 'Fido',
      name2: 'Woofy',
      name3: {
        goodDog: 'Frank',
        badDog: 'Judas',
      }
    },
    poodles: {
      name1: 'Curly',
      name2: 'Fido',
    },
  },
};

เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับออบเจกต์แบบนี้เข้ามา ฟังก์ชันควรหาค่าที่ซ้ำกันทั้งหมดในออบเจกต์ และคืนอาร์เรย์ที่มีค่าซ้ำทั้งหมด

สำหรับออบเจกต์นี้ ผลลัพธ์ควรเป็น:

const output = ['Frank', 'Curly', 'Fido'];

ตัวอย่างโค้ด

const pets = {
  owner1: 'Frank',
  owner2: 'Curly',
  owner3: 'Maurice',
  dogs: {
    terriers: {
      name1: 'Fido',
      name2: 'Woofy',
      name3: {
        goodDog: 'Frank',
        badDog: 'Judas',
      }
    },
    poodles: {
      name1: 'Curly',
      name2: 'Fido',
    },
  },
};
const recursiveSearch = (obj, map = {}, res = []) => {
  Object.keys(obj).forEach(key => {
    if(typeof obj[key] === "object"){
      return recursiveSearch(obj[key], map, res);
    };
    map[obj[key]] = (map[obj[key]] || 0) + 1;
    if(map[obj[key]] === 2){
      res.push(obj[key]);
    }
  });
  return res;
};
console.log(recursiveSearch(pets));

ผลลัพธ์

ผลลัพธ์ที่แสดงในคอนโซลจะเป็นดังนี้:

[ 'Frank', 'Curly', 'Fido' ]