0

enter image description here

I am basically trying to get this problem to work and have isolated the issue to line 21. I think the way I'm trying to access the object key is wrong. I am simply trying to say: if the object key in the new object exists in the original array, push the new value from the new object into the new array.

Edit to add code block

function valueReplace(array, obj) {
  var replaced = [];

  for (var i = 0; i < array.length; i += 1) {
    var value = obj[array[i]];

    if (array.indexOf(obj.i) !== -1) {
      replaced.push(value);
    } else {
      replaced.push(array[i]);
    }
  }
  return replaced;
}
Young Yu
  • 21
  • 1
  • 3
  • 3
    Could you copy and paste the code into the question itself please? Images are really bad way to communicate text & code. – Igor Soloydenko Oct 13 '17 at 20:23
  • @felix-kling, embedding the image into the question makes the code even less readable – Igor Soloydenko Oct 13 '17 at 20:29
  • 1
    What you want is to check whether a property exists. This is explained here: [How to check if object property exists with a variable holding the property name?](https://stackoverflow.com/q/11040472/218196) – Felix Kling Oct 13 '17 at 20:29
  • @IgorSoloydenko: More incentive to replace is with the actual source code then ;) – Felix Kling Oct 13 '17 at 20:30

2 Answers2

0

You have a mixed up error report, but at the actual code, you try to access the object with the property i, obj.i, which not exists. Read more about property accessor.

For getting the wanted result, you might use the in operator for checking if a property in an object exists.

if (array[i] in obj) {
     replaced.push(obj[array[i]]);
} else {
    replaced.push(array[i]);
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

It looks like one of the issues you are having is trying to access a dynamic property with dot notation, which JS generally doesn't like. I reversed your logical if because IMO it makes more sense to see if the object has a property than get a property and then get the index of the array, but you could reverse it back to using index of by array.indexOf(obj[i]) !== -1

function valueReplace(array, obj) {
  let replaced = [];

  for (let i = 0, len = array.length; i < len; i++) {
    if (obj.hasOwnProperty(array[i])) {
      replaced.push(obj[array[i]]);
    } else {
      replaced.push(array[i]);
    }
  }
  return replaced;
}

Because I generally like simplifying things here is this functionality rewritten in ES6 compatible code, using array.prototype.map. Don't use it for your homework, but if you want you can work it backwards into a standard function ;).

const valueReplace = (array, obj) => array.map(val => (obj.hasOwnProperty(val)) ? obj[val] : val);
D Lowther
  • 1,609
  • 1
  • 9
  • 16