-1

I loop through an array called accData and make a new array called WL and RF. I want to make it easy to maintain, but I have a problem. When I want to change the WL array data to CH2 and RF array data to DIG2, I have to type the script manually. This is my script

const accData = [
    { st: 'serijabo', path: 'serijabo.json', wl: 'CH1', rf: 'DIG1' },
    { st: 'sukabumi', path: 'sukabumi.json', wl: 'CH2', rf: 'DIG2' },
];

for (let i = 0; i < accData.length; i++) {
  const xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    const data = JSON.parse(xhr.responseText);

    let WL = [];
    let RF = [];
    for (let i = 0; i < data.length; i++) {
      WL.push(Number(data[i].CH1)); // this line
      RF.push(Number(data[i].DIG1)); // and this line
    }
  }
 }
}

I try to use ES6 template to solve it but it is not working because the template must be place in a string.

WL.push(Number(data[i].`${accData[i].wl}`)); //not working
RF.push(Number(data[i].`${accData[i].rf}`)); //not working

How can I solve this?

7
  • Is that Number() really necessary? Commented Aug 30, 2019 at 18:02
  • Possible duplicate of JavaScript object declaration syntax - variable names as properties Commented Aug 30, 2019 at 18:07
  • yes, because json returns string and i want to process number, so i convert it @Vilx- Commented Aug 30, 2019 at 18:08
  • duplicate of stackoverflow.com/questions/11043026/… and so many hundreds of other questions about the same thing. Commented Aug 30, 2019 at 18:08
  • You use i twice.... That is your major issue Commented Aug 30, 2019 at 18:11

1 Answer 1

0

Have you tried using brackets instead of a dot? They should allow you to access properties via a string.

WL.push(Number(data[i][`${accData[i].wl}`]));
RF.push(Number(data[i][`${accData[i].rf}`]));
Sign up to request clarification or add additional context in comments.

14 Comments

Also i has been redefined in the callback.
Not to mention the whole string expression is totally unnecesary. Just do data[i][accData[i].rf]
the data[i][accData[i].wl] returns error "Uncaught TypeError: Cannot read property 'wl' of undefined" while the data[i].CH1 works fine
If you're getting that error it means the object accData[i] doesn't exist at some moment for you to access its wl property. You can write accData[i] && WL.push(Number(data[i][`${accData[i].wl}`])); so the code will only run when accData[i] exists.
and the (data[i]['{accData[i].wl}']) returns NaN for every element
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.