Turn array of objects into list of options having label and value

Viewed 722

I need to transform a JSON object to be a specific structure so it feeds into a select tag.

I tested it outside the codebase and it worked, but now I don't know where the problem is. My select tag still appears empty

Here is the example select bar

Here is my codesandbox

Here is the structure I need:

const options = [
  { value: "Alabama A & M University", label: "Alabama A & M University" },
  { value: "Amridge University", label: "Amridge University" },
  { value: "University of Alabama at Birmingham", label: "University of Alabama at Birmingham" }
];

a array of objects with value and label keys

Here is the original structure:

const institutions = [
    {
      "institution": "Alabama A & M University"
    },
    {
      "institution": "University of Alabama at Birmingham"
    },
    {
      "institution": "Amridge University"
    }]

Here is how I am manipulating the code:

export const transformCollegeJSON =(institutions = [])=> {
  let result = [];

    for(let k = 0; k <= institutions.length; k++){   
            result.push({
            "value":institutions[college]['institution'],
            "label":institutions[college]['institution']
        })
    }
    return result
}
2 Answers

Simple as that:

const src = [
    {
      "institution": "Alabama A & M University"
    },
    {
      "institution": "University of Alabama at Birmingham"
    },
    {
      "institution": "Amridge University"
    }],
    
    result = src.map(({institution:value}) => ({value, label:value}))
    
console.log(result)    

If you want to code to work, replace <= by < in the for parenthesis and replace college by k

const transformCollegeJSON = (institutions = []) => {
    let result = [];

    for (let k = 0; k < institutions.length; k++) {
        result.push({
            "value": institutions[k]['institution'],
            "label": institutions[k]['institution']
        })
    }
    return result
}

const institutions = [{
        "institution": "Alabama A & M University"
    },
    {
        "institution": "University of Alabama at Birmingham"
    },
    {
        "institution": "Amridge University"
    }
]

console.log(transformCollegeJSON(institutions))

Related