how can i loop through an array to generate objects - reactjs

I want to loop through an array to generate a customized object array
const frequencies = [
{
value: "none",
label: "None",
},
{
value: "1_month",
label: "1 month",
},
{
value: "2_month",
label: "2 month",
},
];
const loop = {[...new Array(10)].map((_, index) => {
return [
{
value: index,'month',
label: index,'month',
},
];
})}

You're assigning a object {} to the loop variable which you then try to add a array to without a key. This is not working. When returning from the map function you return a array [].
You can use the index in a string with the `${index} month` syntax:
const loop = [...new Array(10)].map((_, index) => {
return [
{
value: `${index}_month`,
label: `${index} month`,
},
];
});
console.log(loop);

Related

How can I add the first to the array in useState in React?

I have an array object called tempArr.
When I run a function called fetchLifeCycle, i want to act setPickerItems(tempArr); is mandatory first, and then setPickerItems([...tempArr, { label: 'Not selected', value: "NONE" }]) .
As a result, { label: 'not selected', value: "NONE" } was added at the end.
But I want to add that object to the first object of pickerItems. How do I do that?
this is my code
tempArr = [
{ label: "hi", value: 'egg' },
{ label: "bye", value: 'insect' },
{ label: "woo", value: 'pest' },
{ label: "pick", value: 'hambuger' },
]
const [pickerItems, setPickerItems] = useState([])
const fetchLifeCycle = () => {
setPickerItems(tempArr);
setPickerItems([...tempArr, { label: '선택안함', value: "NONE" }])
}
expected answer
pickerItems = [
{ label: '선택안함', value: "NONE" }
{ label: "hi", value: 'egg' },
{ label: "bye", value: 'insect' },
{ label: "woo", value: 'pest' },
{ label: "pick", value: 'hambuger' },
]
tempArr = [
{ label: "hi", value: 'egg' },
{ label: "bye", value: 'insect' },
{ label: "woo", value: 'pest' },
{ label: "pick", value: 'hambuger' },
]
const updated = [{ label: '선택안함', value: "NONE" }, ...tempArr]
console.log('updated', updated)
You just have to reverse the order:
setPickerItems([{ label: '선택안함', value: "NONE" }, ...tempArr])
You can put the new item first, then spread the existing array:
setPickerItems([{ label: '선택안함', value: "NONE" }, ...tempArr])
Just simple:
setPickerItems([{ label: '선택안함', value: "NONE" }, ...tempArr])

get key values pair from an array of objects and place in new array

I need to keep { label: "Strawberry 🍓", value: "strawberry"}, for this code to work with
the in react though when submitting to the database i would like to have the selected values sent through as strawberry: true, watermelon: true, pear: true,
const options = [
{ label: "Strawberry 🍓", value: "strawberry"},
{ label: "Watermelon 🍉", value: "watermelon" },
{ label: "Pear 🍐", value: "pear" },
]
I would like to convert the above array to an array of
const newArray = [
strawberry: true
watermelon: true
pear: true
]
I would have a clue how you would do it maybe it's a two step thing?
If you really mean an object {strawberry: true, watermelon: true, pear: true} (an associative array), not an Array,
const options = [
{ label: "Strawberry 🍓", value: "strawberry"},
{ label: "Watermelon 🍉", value: "watermelon" },
{ label: "Pear 🍐", value: "pear" },
];
const optionsObject = {};
options.forEach(({value}) => optionsObject[value] = true);
(You can also do this with .reduce if you really want to:)
const optionsObject = options.reduce((obj, {value}) => {
obj[value] = true;
return obj;
}, {});

Filter Array based on a property in the array of its objects

Given is following data structure
const list = [
{
title: 'Section One',
data: [
{
title: 'Ay',
},
{
title: 'Bx',
},
{
title: 'By',
},
{
title: 'Cx',
},
],
},
{
title: 'Section Two',
data: [
{
title: 'Ay',
},
{
title: 'Bx',
},
{
title: 'By',
},
{
title: 'Cx',
},
],
},
];
What i want to do ist to filter this list based on title property in the data array of each object.
An example would be to have the list where the title property of the childs starts with "B", so the list will look like that:
const filteredList = [
{
title: 'Section One',
data: [
{
title: 'Bx',
},
{
title: 'By',
}
],
},
{
title: 'Section Two',
data: [
{
title: 'Bx',
},
{
title: 'By',
}
],
},
];
What i tried so far was something like that:
const items = list.filter(item =>
item.data.find(x => x.title.startsWith('A')),
);
or
const filtered = list.filter(childList => {
childList.data.filter(item => {
if (item.title.startsWith('B')) {
return item;
}
return childList;
});
});
But i think i am missing a major point here, maybe some of you could give me a tip or hint what i am doing wrong
Best regards
Your issue is that you're doing .filter() on list. This will either keep or remove your objects in list. However, in your case, you want to keep all objects in list and instead map them to a new object. To do this you can use .map(). This way you can map your objects in your list array to new objects which contain filtered data arrays. Here's an example of how you might do it:
const list=[{title:"Section One",data:[{title:"Ay"},{title:"Bx"},{title:"By"},{title:"Cx"}]},{title:"Section Two",data:[{title:"Ay"},{title:"Bx"},{title:"By"},{title:"Cx"}]}];
const filterByTitle = (search, arr) =>
arr.map(
({data, ...rest}) => ({
...rest,
data: data.filter(({title}) => title.startsWith(search))
})
);
console.log(filterByTitle('B', list));

How to modify Array on React

In api return value like this,
[
"Action",
"Comedy",
"Documentary",
"Drama"
]
I need to modify the above array like this,
const techCompanies = [
{ label: "Action", value: 1 },
{ label: "Comedy", value: 2 },
{ label: "Documentary", value: 3 },
{ label: "Drama", value: 4 }
];
I used Axios to get data,
const response = await axios.get("http://localhost:3000/Movie/v1.0/genre");
This is an array so you can you use the .map() function to do that:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
const arr = ["Action", "Comedy", "Documentary", "Drama"];
arr.map((arrElement, index) => ({ label: arrElement, value: index }));

Populate my options data with react-select from API?

This doesn't seem to be working when i try to populate my data with the data i fetched from my API. I am currently fetching the data, storing it in my array called ProductsAndAirlines which i instantiated in my constructor, then I am setting the data values dynamically in my options,but currently it doesn't. It only inserts the first static value which is PBS.
Code
getProductsAndAirlines = _ => {
fetch('http://localhost:4000/allProductAndAirlineValuesInJira')
.then(res => res.json())
.then( res =>
this.setState({ ProductsAndAirlines: res.data }
))
.catch(err => console.error(err))
}
componentDidMount() {
this.getAirlines();
this.getProductsAndAirlines();
setTimeout(() => {
this.setState({ show: true });
}, 10);
}
const optionsProduct = [
ProductsAndAirlines && ProductsAndAirlines.projects && Object.keys(ProductsAndAirlines.projects).map((issue, i) => (
ProductsAndAirlines.projects[0].issuetypes[0].fields.customfield_11600.allowedValues && Object.keys(ProductsAndAirlines.projects[0].issuetypes[0].fields.customfield_11600.allowedValues ).map((product, product_index) => (
{value: ProductsAndAirlines.projects[0].issuetypes[0].fields.customfield_11600.allowedValues[product_index].value, label: ProductsAndAirlines.projects[0].issuetypes[0].fields.customfield_11600.allowedValues[product_index].value}
))
))
render(){
<Select
placeholder = {this.state.Product}
onChange={this.handleChangeProduct}
options={optionsProduct()}
/>
}
It's, probably, because your map function is wrong somehow. If you take a deep look you can check, for each key in ProductsAndAirlines.projects, the map function is returning an entirely new array. in the end, the options are being like
[
[{ value: 'PBS', label: 'PBS' },
{ value: 'Pairing', label: 'Pairing' },
{ value: 'MPP - Insight', label: 'MPP - Insight' },
{ value: 'BLISS', label: 'BLISS' },
{ value: 'Shiftlogic', label: 'Shiftlogic'}
]],
[{ value: 'PBS', label: 'PBS' },
{ value: 'Pairing', label: 'Pairing' },
{ value: 'MPP - Insight', label: 'MPP - Insight' },
{ value: 'BLISS', label: 'BLISS' },
{ value: 'Shiftlogic', label: 'Shiftlogic'}
]]
]

Resources