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;
}
6
  • 1
    did you forget to put a semi-colon on your declaration? Commented Oct 9, 2018 at 23:09
  • @AlexisVillar that's valid JavaScript. Commented Oct 9, 2018 at 23:10
  • What have you tried so far? Commented Oct 9, 2018 at 23:11
  • @clabe45 I really didn't try anything since I had no idea how to even approach this. Commented Oct 9, 2018 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. Commented Oct 9, 2018 at 23:14

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.