How to Change Data in React - reactjs

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.

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);

You just need to do
const createData = (data) => {
return data.map(d => ({name: data.name, label: data.name}))
};
const option = createData(data)

Related

filter an object and get rid of an attribute using react JS

Objects:[
{id:'a',
owner: 'b',
products:[{productId:'a1',name:'b1'},{productId:'a2',name:'b2'}]
date: '2-2'},
{id:'e',
owner: 'f',
products:[{productId:'a3',name:'b3'},{productId:'a4',name:'b4'}]
date: '1-1'}
{id:'g',
owner: 'y',
products:[{productId:'a4',name:'b3'},{productId:'a7',name:'b9'}]
date: '1-3'}
]
Result:
[{id:'e',
owner: 'f',
products:[{productId:'a3',name:'b3'}]
date: '1-1'}
{id:'g',
owner: 'y',
products:[{productId:'a4',name:'b3'}]
date: '1-3'}]
In above example, how do I get the second object by the value of name:'b3'? and get rid of this part {productId:'a4',name:'b4'} The name is an attribute of products array and products is an attribute of objects array. I'll appreciate if someone can help me out.
You could practically achieve the result you desire in 2 steps, first by using Array.find to find the object. And then by using Array.filter to filter out all other products. Like this:
const objects = [
{
id: 'a',
owner: 'b',
products: [
{ productId: 'a1', name: 'b1' },
{ productId: 'a2', name: 'b2' },
],
date: '2-2',
},
{
id: 'e',
owner: 'f',
products: [
{ productId: 'a3', name: 'b3' },
{ productId: 'a4', name: 'b4' },
],
date: '1-1',
},
];
const searchVal = 'b3';
let result = objects.find((obj) => obj.products.some((p) => p.name === searchVal));
if (result) {
result = {
...result,
products: result.products.filter((r) => r.name === searchVal)
}
}
console.log(result);
If you're planning using this approach on multiple different places in your code, then you could also create a function to handle it for you:
const objects = [
{
id: 'a',
owner: 'b',
products: [
{ productId: 'a1', name: 'b1' },
{ productId: 'a2', name: 'b2' },
],
date: '2-2',
},
{
id: 'e',
owner: 'f',
products: [
{ productId: 'a3', name: 'b3' },
{ productId: 'a4', name: 'b4' },
],
date: '1-1',
},
];
const getObjectWithFilteredProducts = (objArr, searchVal) => {
let result = objects.find((obj) => obj.products.some((p) => p.name === searchVal));
if (result) {
result = {
...result,
products: result.products.filter((r) => r.name === searchVal),
};
}
return result;
};
console.log(getObjectWithFilteredProducts(objects, 'b3'));
EDIT
If you want an array as your result, you could do it like this:
const objects = [
{
id: 'a',
owner: 'b',
products: [
{ productId: 'a1', name: 'b1' },
{ productId: 'a2', name: 'b2' },
],
date: '2-2',
},
{
id: 'e',
owner: 'f',
products: [
{ productId: 'a3', name: 'b3' },
{ productId: 'a4', name: 'b4' },
],
date: '1-1',
},
];
const searchVal = 'b3';
const result = objects.reduce((acc, obj) => {
if (obj.products.some((p) => p.name === searchVal)) {
return [
...acc,
{
...obj,
products: obj.products.filter((p) => p.name === searchVal),
},
];
}
return acc;
}, []);
console.log(result);
I guess you can do something like this. Your existing filter will find the top level object that contains a product with the correct name. If that object is found, you can then filter the array of products, matching on searchValue
const tempObjects = Objects.filter((obj) => hasProductsByName(obj.products))
let products = []
temp.forEach(
(obj) =>
(products = products.concat(
obj.products.filter((product) => product.name === searchValue)
))
)
products should now contain all products matching the searchValue

Update a selected property from react state of objects with arrays

Assume that this state has initial data like this
const [options, setOptions] = useState({
ProcessType: [
{ value: 1, label: 'Type1' }, { value: 2, label: 'Type2' }
],
ResponsibleUser: [
{ value: 1, label: 'User1' }, { value: 2, label: 'User2' }
]
});
The following function will be called again and again when a post/put called
Help me to complete the commented area as described there.
const fetchProcesses = async () => {
await axios.get(`${process.env.REACT_APP_SERVER_BASE_URL}/processes/`)
.then((result) => {
/*
I want here to clear the existing data in options.ProcessType and
map result.data as { value: result.data.id , label: result.data.name },....
and push/concat it into to options.ProcessType but i want to keep the data
inside options.ResponsibleUser unchanged.
result.data is an array of objects like this,
[
{ id: 1 , name: 'Type1', desc : 'desc1', creator: 3, status: 'active' },
{ id: 2 , name: 'Type2', desc : 'desc2', creator: 6, status: 'closed' },
.....
.....
]
*/
})
}
Here is a solution
const fetchProcesses = async () => {
await axios.get(`${process.env.REACT_APP_SERVER_BASE_URL}/processes/`)
.then((result) => {
// solution
setOptions({ResponsibleUser: [...options.ResponsibleUser], ProcessType: result.data.map(row => ({value: row.id, label: row.name}))})
})
}

How to Initialise leaf/child stores of MobX State Tree

My MobX State tree Model is like this
const ProductItem = types
.model({
name: types.string,
price: types.number
})
.actions(self => ({
changePrice(newPrice) {
self.price = newPrice;
}
}));
const ProductStore = types
.model({
items: types.optional(types.array(ProductItem), [])
})
.actions(self => ({
add(item) {
self.items.push(item);
}
}));
const AppStore = types.model('AppStore', {
productStore: types.maybeNull(ProductStore)
});
AppStore is root store.
I want to create AppStore and initialize below data for ProductStore. I've created below function to initialize and create store :
export const initializeStore = (isServer, snapshot = null) => {
if (isServer) {
AppStore.create({
.....
});
}
return store;
};
I'm not sure how ProductStore should be initialized inside AppStore.create() with this array :
items: [
{
name: 'Product 1',
price: 150
},
{
name: 'Product 2',
price: 170
}
]
any help would be appreciated.
The initial data can be given like this
AppStore.create({
productStore: {
items: [
{
name: 'Product 1',
price: 150
},
{
name: 'Product 2',
price: 170
}
]
}
});
as ProductStore is used under productStore key in your AppStore.

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 return an object with an array within an array

Need to return as an object or a better way of extracting data from the following data model.
const dataModel = {
data:[
{
id: '1234',
entity : [{
id: '1',
type: 'books'
}]
},
{
id: '1234',
entity : [{
id: '1',
type: 'books'
}]
}
]
};
I have tried the following code
const getBooksId = response.data.map(values => {
return values.entity.find(entity =>
entity.type === 'books'
);
}).filter( data => data !== undefined);
}
const getMagazineId = response.data.map(values => {
return values.entity.find(entity =>
entity.type === 'magazine'
);
}).filter( data => data !== undefined);
}
let getDataIntoObject = { bookId: getBooksId[0].id, magazineId: getMagazine[0].id }
The getDataIntoObject gives me the expected result which is the id of each entity but the code looks messy. Is there a better way of doing this?
Here is a version that looks a bit nicer:
const responseData = [
{
id: '123',
entity: [{
id: '1',
type: 'books'
}]
},
{
id: '456',
entity: [{
id: '2',
type: 'books'
}]
},
{
id: '789',
entity: [{
id: '3',
type: 'magazine'
}]
}
];
const entities = responseData.map(d => d.entity).flat();
const book = entities.find(e => e.type === 'books');
const magazine = entities.find(e => e.type === 'magazine');
const getDataIntoObject = {
bookId: book && book.id,
magazineId: magazine && magazine.id
};
console.log(getDataIntoObject);
...and handles a book or magazine not being found.

Resources