0

I know the syntax is wrong, but in the following code key is supposed to equal the object's key. As the loop iterates, key gets assigned the i value, so a:1, b:2...etc.

var objArr = [
  {a: null},
  {b: null},
  {c: null}
];

for (var i = 0; i < objArr.length; i++) {
    objArr[i].key = i;
}
  • 1
    did you forget to put a semi-colon on your declaration? – Alexis Villar Oct 09 '18 at 23:09
  • @AlexisVillar that's valid JavaScript. – clabe45 Oct 09 '18 at 23:10
  • What have you tried so far? – clabe45 Oct 09 '18 at 23:11
  • @clabe45 I really didn't try anything since I had no idea how to even approach this. –  Oct 09 '18 at 23:12
  • Think about your problem. You want to assign an incrementing number to a corresponding letter in the array of objects. You're on the right track, but you're setting the `key` property of each object. One way is to [convert the integer to a letter](https://stackoverflow.com/a/13202079/3783155). – clabe45 Oct 09 '18 at 23:14
  • Possible duplicate of [Get the value of an object with an unknown single key in JS](https://stackoverflow.com/questions/32208902/get-the-value-of-an-object-with-an-unknown-single-key-in-js) – Heretic Monkey Oct 09 '18 at 23:15

1 Answers1

1

Assuming the objects only contain one key, you can find the key using Object.keys[0]:

var objArr = [
  {a: null},
  {b: null},
  {c: null}
];
objArr.forEach((obj, i) => {
  const key = Object.keys(obj)[0];
  obj[key] = i;
});
console.log(objArr);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320