JavaScript Interview Question - 18 | Deep flatten an object

แชร์
ฝัง
  • เผยแพร่เมื่อ 19 ต.ค. 2024

ความคิดเห็น • 10

  • @al8905
    @al8905 ปีที่แล้ว +1

    I'm relatively new to js and your videos have helped me a lot so thank you

  • @nocode659
    @nocode659 ปีที่แล้ว +1

    U are great sir. I hope to be like you one day.. js god

    • @Learnersbucket
      @Learnersbucket  ปีที่แล้ว +1

      Thank you for your kind words, but I am still an apprentice. You can never master an evolving programming language.

  • @SoumyaCode
    @SoumyaCode ปีที่แล้ว +1

    You are really putting out great content man , Appericiate your Hardwork and effort 🙏. Please keep publishing great videos .

  • @themeniacs7376
    @themeniacs7376 ปีที่แล้ว +1

    🔥

  • @urveshgodhani4542
    @urveshgodhani4542 ปีที่แล้ว +2

    const nested = {
    A: "12",
    B: 23,
    C: {
    P: 23,
    O: {
    L: 56
    },
    Q: [1, 2]
    }
    };
    function isObject(obj) {
    return typeof (obj) === "object" && obj !== null && !Array.isArray(obj);
    }
    function isArray(obj) {
    return typeof (obj) === "object" && obj !== null && Array.isArray(obj);
    }
    function flatten(nested) {
    const obj = {};
    const nestedKeys = Object.keys(nested);
    nestedKeys.map((Element) => {
    if (isObject(nested[Element])) {
    const returnObj = flatten(nested[Element]);
    const returnObjKeys = Object.keys(returnObj);
    returnObjKeys.map((element) => {
    obj[Element + "." + element] = returnObj[element];
    })
    }
    else if (isArray(nested[Element])) {
    for (let i = 0; i < nested[Element].length; i++) {
    obj[Element + "." + +i] = nested[Element][i]
    }
    }
    else {
    obj[Element] = nested[Element];
    }
    })
    return obj
    }
    console.log(flatten(nested));
    Any suggestions for improvement?

    • @Learnersbucket
      @Learnersbucket  ปีที่แล้ว

      Unncessary array check, as arrays are object only in javascript, we can iterate them using the for...in loop.
      Also code is very verbose, keep it simple, so that it is easy readable and understandable.