K
K
KirillEX2020-02-08 16:28:38
JavaScript
KirillEX, 2020-02-08 16:28:38

Why doesn't the recursive call work?

let a = {
  name: "Marshall",
  age: 47,
  child: {
    name: "Haley",
    age: 24
  }
};

function deepEqual(obj) {
  let sort = Object.entries(obj);
  sort = sort.sort()
  obj = Object.fromEntries(sort);
  for (let key in obj) {
    if (typeof key === "object") {
      deepEqual(key)
    }
  };
  return obj;
};
console.log(deepEqual(a))

Why doesn't recursive sort work? The object itself is sorted, but its object property is not.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Suha, 2020-02-08
@KirillEX

if (typeof key === "object") {
      deepEqual(key)
    }

Change to
if (typeof obj[key] === "object") {
      deepEqual(obj[key])
    }

https://developer.mozilla.org/uk/docs/Web/JavaScript...

S
Sergey delphinpro, 2020-02-08
@delphinpro

Classical "plugging" in recursion.
The function deepEqual returns a sorted object.
Where does the return value (nested object) go?

if (typeof key === "object") {
      deepEqual(key)
    }

Nowhere. It sorts in the next levels of recursion, but does not return back.
I guess it should be like this:
if (typeof key === "object") {
      obj[key] = deepEqual(key)
    }

UPD
And anyway, for..in iterates over the object's keys, not their values!
Offhand:
obj = Object.fromEntries(sort);
for (let key in obj) {
  if (!obj.hasOwnProperty(key)) continue;
  let subObj = obj[key];
  if (typeof subObj === "object") {
    obj[key] = deepEqual(subObj)
  }
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question