Can you pass an object key as a param? - Svelte/JS

Viewed 199

I'm using Svelte and my component wants to take in an array of objects and a specific key. However it doesn't want to read the key when it is a variable. This is what I've tried so far.

  export let data = [];
  export let key;
  function cleanUp(data, key) {
    for (let i = 0; i < data.length; i++) {
      let d = data[i].key;
      newArray.push(d);
    }
  }

Is there anyway to make this work?

1 Answers

If the key variable contains a string, you can access an object's property with that name with object[key].

In your example:

let d = data[i][key];
Related