Home > database >  How to Change Data in React
How to Change Data in React

Time:01-18

I want to create data from DATA to OPTIONS.

const DATA = [
    { name: 'aaa', id: 'happy' },
    { name: 'bbb', id: 'time' },
    { name: 'ccc', id: 'party' },
  ];

const OPTIONS =[{value:'aaa', label:'aaa'},
                {value:'bbb', label:'bbb'},
                {value:'ccc', label:'ccc'},
               ]

I need only name value in DATA. so, using name value, I want to create OPTIONS.

Fuction Test(){

const DATA = [
    { name: 'aaa', id: 'happy' },
    { name: 'bbb', id: 'time' },
    { name: 'ccc', id: 'party' },
  ];

const OPTIONS =[{value:'aaa', label:'aaa'},
                {value:'bbb', label:'bbb'},
                {value:'ccc', label:'ccc'},
               ]
}
let newObject=[];

const createData = () => {
    const arr = selectMainId.data.map(data => data.name);
    arr.map(data => newObject.push({ value: data, label: data }));
    console.log('newObj:', newObject);
  };
console.log('newObj1:', newObject))

this case, I can get OPTIONS same data. so, I can get newObject in createData console. but I can't get newObject in Test console. I don't know this issue. Do you know effective way? please help me.

CodePudding user response:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Clean and simplest way:

const DATA = [
    { name: 'aaa', id: 'happy' },
    { name: 'bbb', id: 'time' },
    { name: 'ccc', id: 'party' },
];

const OPTIONS = DATA.map(x => ({value: x.name, label: x.name }));

console.log(OPTIONS);

CodePudding user response:

You just need to do

const createData = (data) => {
  return data.map(d => ({name: data.name, label: data.name}))
};

const option = createData(data)
  •  Tags:  
  • Related