0

I have an object. I pull the keys and values and place in separate arrays. I then put them back together but in reverse. It keeps placing the second item first.

const obj = { keyname: 'Greg', keyage: 40, keyjob: 'cook'};
console.log(_.invert(obj));

    invert (object) {
      let keyArr = Object.keys(object);
      let valueArr = Object.values(object);
      const result = {};
      valueArr.forEach((value, i) => result[value] = keyArr[i]);
      return result;
    }

I am expecting to get a result of

{ Greg: 'keyname', 40: 'keyage', cook: 'keyjob' }

but instead i get

{ '40': 'keyage', Greg: 'keyname', cook: 'keyjob' }

why?

degsX2
  • 1
  • Keys that look like numbers always come first. The ordering of property names is defined in the spec but it is a very, very fragile practice to rely on it. – Pointy Oct 28 '21 at 16:56
  • I was just looking up a different way to add them in. I was unaware of ordering and am glad I have found this. I was looking at object.assign and found my way to .map. Thank you for the quick responses. – degsX2 Oct 28 '21 at 17:06

0 Answers0