Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show original order of object properties in console.log

I need for some debugging to see the original order of one JavaScript object's properties but (at least in chrome devtools) console.log() shows me an alphabetically ordered object.

Ex:

var obj = {
    z: 1,
    t: 2,
    y: 3,
    a: 4,
    n: 5,
    k: 6
}

console.log(obj) shows this:

Object {z: 1, t: 2, y: 3, a: 4, n: 5…}
a:4
k:6
n:5
t:2
y:3
z:1

//expected (needed ) original order
z: 1
t: 2
y: 3
a: 4
n: 5
k: 6
like image 497
MTK Avatar asked Aug 20 '16 13:08

MTK


People also ask

How do you sort an object property?

Sort-Object uses the Property parameter with a hash table to specify the property names and sort orders. The Property parameter is sorted by two properties, Status in descending order and DisplayName in ascending order. Status is an enumerated property. Stopped has a value of 1 and Running has a value of 4.

How do you display an object in console log?

Answer: Use console. log() or JSON. stringify() Method This method will print the object in browser console.

Does object keys preserve order?

YES (but not always insertion order). Most Browsers iterate object properties as: Integer keys in ascending order (and strings like "1" that parse as ints) String keys, in insertion order (ES2015 guarantees this and all browsers comply)

How do you find the first property of an object?

To access the first property of an object, pass the object to the Object. values method and access the element at index 0 , e.g. Object. values(obj)[0] .


1 Answers

Objects do retain the order that their (non-numeric) keys were inserted in, but they are only guaranteed to iterate in that order using certain methods. Per the specification, Object.keys and its variants, JSON.stringify, and for..in loops all iterate in an unspecified order. These methods all call EnumerateObjectProperties, which explicitly states:

The mechanics and order of enumerating the properties is not specified

While environments generally iterate in the predictable order anyway for those methods, that behavior is in no way guaranteed by the specification.

But, Object.getOwnPropertyNames (and Reflect.ownKeys, and Object.getOwnPropertySymbols) are guaranteed to iterate in a particular order: ascending numeric keys, followed by other keys in insertion order, per [[OwnPropertyKeys]].

So, a specification-guaranteed method of logging (non-numeric) properties in insertion order will involve using one of the above methods, rather than Object.keys or its variants:

var obj = {
  z: 1,
  t: 2,
  y: 3,
  a: 4,
  n: 5,
  k: 6
};

const str = '{\n' +
  Object.getOwnPropertyNames(obj).map(key => `  ${key}: ${obj[key]}`).join('\n')
  + '\n}';
console.log(str);

For nested objects, you'll need a recursive function instead:

var obj = {
  z: 1,
  t: 2,
  y: 3,
  a: 4,
  nested: {
    foo: 9,
    bar: 99,
    baz: 35
  },
  n: 5,
  k: 6
};

const objToArrOfLines = (obj, lines=[], leftPadding=0, keyForThisObj) => {
  lines.push(`${' '.repeat(leftPadding)}${keyForThisObj ? keyForThisObj + ': ' : ''}{`);
  Object.getOwnPropertyNames(obj).forEach((key) => {
    const val = obj[key];
    if (typeof val === 'object') {
      objToArrOfLines(val, lines, leftPadding + 2, key);
    } else {
      lines.push(`${' '.repeat(leftPadding + 2)}${key}: ${val}`);
    }
  });
  lines.push(`${' '.repeat(leftPadding)}}`);
  return lines;
};
const objToStr = (obj) => {
  console.log(objToArrOfLines(obj).join('\n'));
};

objToStr(obj);
like image 96
CertainPerformance Avatar answered Sep 30 '22 22:09

CertainPerformance