2

I have an array which has following String values - ['WATER','ENERGY','PAPER','FOOD SAFETY','FOOD AND BEVERAGE', 'INSTITUIONAL','PEST']

Im trying to convert this into an array of objects with a key and value pair but unable to do so. Here is my code:

 handleFavOptions(result){
        console.log('divisions data in handleFavOptions', result);
        this.divisionFilterOptions = [];
        this.tempArray = result.map((key) => (
            {
                label: key, 
                value: result[key]
                
            }
        ));
        console.log('temp array is',this.tempArray);

the first console log is showing proper output as below: enter image description here

But surpringly in the following code the console shows empty Array

 this.tempArray = result.map((key) => (
            {
                label: key, 
                value: result[key]
                
            }
        ));
        console.log('temp array is',this.tempArray); // Shows blank

Am I iterating in the wrong way? I need in this form where there is a label and key. And the label and key will both be same.

3
  • Can you clarify what you want the keys in your object to be?
    – fred
    Jun 22, 2023 at 16:33
  • it will be a list of those unique divisions itself. Means label and value will be holding the same values. Key will be unique since the list itself will hold only unique values
    – Amax1
    Jun 22, 2023 at 16:47
  • Ok, thank you, I will update my answer
    – fred
    Jun 22, 2023 at 16:48

1 Answer 1

1

result is an Array, and key is an item in the array (e.g. "PAPER"). So doing result[key] is going to be undefined.

Since you want the label and value to be the same in your object, you would do the following:

this.tempArray = result.map((key) => (
    {
        label: key, 
        value: key
            
    }
));
2
  • so do I need to map both label and value to the key itself?, what will the conversion look like inside the iteration?
    – Amax1
    Jun 22, 2023 at 16:49
  • @Amax1 yes. Does that answer?
    – fred
    Jun 22, 2023 at 16:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .