Omar Hussein
Omar Hussein

Reputation: 1147

Create Array List dynamically from Javascript Object

Alright, so I'd like to create a selector with different US States, I'll be using this package, which for the input:

var usStates = new UsaStates();
console.log(usStates.states);`

outputs:

{
    name: "Alabama",
    abbreviation: "AL",
    territory: false,
    capital: "Montgomery",
    contiguous: true
},
{
    name: "Alaska",
    abbreviation: "AK",
    territory: false,
    capital: "Juneau",
    contiguous: false
},
...(other states omitted for brevity)
{
    name: "Wyoming",
    abbreviation: "WY",
    territory: false,
    capital: "Cheyenne",
    contiguous: true
}

I already have a selector component, but it takes options as an array prop like so:

<LNSelect
                options={[
                  { label: "Alabama", value: "AL" },
                  { label: "New York", value: "NY" },
                ]}
></LNSelect>

How can I use the package's functionality to create an Array in the necessary format with label as the name and value as the abbreviation?

Many thanks!

Upvotes: 1

Views: 69

Answers (2)

Yannick K
Yannick K

Reputation: 5422

Besides being able to map it yourself just using JS, the documentation specifies you can create a custom format, which for you would be:

var myCustomStates = usStates.format({
    $label: 'name',
    $value: 'abbreviation',
});

Where the '$' translates to the literal string you want, and otherwise the package attempts to link specific values to the key/value (e.g. 'name' would become "New York", and '$name' would simply become 'name').

(For any package, just read the documentation first.)

Upvotes: 1

Fdebijl
Fdebijl

Reputation: 1041

Transforming arrays is usually done with map. Simply call map on the array of states if it's already provided in that format, or use Object.entries() to transform the object to an array for use with map.

const states = [{
    name: "Alabama",
    abbreviation: "AL",
    territory: false,
    capital: "Montgomery",
    contiguous: true
},
{
    name: "Alaska",
    abbreviation: "AK",
    territory: false,
    capital: "Juneau",
    contiguous: false
},
{
    name: "Wyoming",
    abbreviation: "WY",
    territory: false,
    capital: "Cheyenne",
    contiguous: true
}];

const options = states.map(state => {
  return {
    label: state.name,
    value: state.abbreviation
  }
});

console.log(options);

Upvotes: 2

Related Questions