stack blunter
stack blunter

Reputation: 39

How to make a new object in an array

I have an autocomplete and when the user clicks on it it adds the value to the end of the label and value key.

I have an array object like this:

I want to transform my array object like this:

{label: "8", value: "8"}
{label: "10", value: "10"}
{label: "9", value: "9"}

I have tried transforming it like so:

  const edit = scheduleFieldData['project'].split(/,(?=")/).map(x => ({label: x, value: x}))

But instead I get this:

    [
       {"label":",8,10,9","value":",8,10,9"}
    ]

Any JS Gurus know how to do this? Much help is appreciated!

the value of scheduleFieldData['project'] returns a string :

,8,9

Upvotes: 1

Views: 41

Answers (1)

Julian Kleine
Julian Kleine

Reputation: 1547

Just split by "," and filter for undefined or null values. You can even add a sort.

const test = ',8,10,9';

const edit = test.split(",").filter(x => x).sort((a,b) => a - b).map(x => ({
  label: x,
  value: x
}));

console.log(edit)

Upvotes: 1

Related Questions