I have here an array of datas. And I want to update the title from the object where the key is 3.
const data = [
{
key: '1',
title: 'Title 1',
desc: 'Desc 1',
image: 'http://192.168.0.22:3000/build/photo_1621612104216_d747ced4-b313-4687-b9ac-ab5bcd78501d.jpg'
},
{
key: '2',
title: 'Title 2',
desc: 'Desc 2',
image: 'http://192.168.0.22:3000/build/photo_1621612230526_f49f2be8-6fd6-420d-b0b0-b39216418924.jpg'
},
{
key: '3',
title: 'Title 3',
desc: 'Desc 3',
image: 'http://192.168.0.22:3000/build/photo_1621612230526_f49f2be8-6fd6-420d-b0b0-b39216418924.jpg'
},
{
key: '4',
title: 'Title 4',
desc: 'Desc 4',
image: 'http://192.168.0.22:3000/build/photo_1621612104216_d747ced4-b313-4687-b9ac-ab5bcd78501d.jpg'
},
];
How I make it?
..............
.............
............
..........
...........
............
..............
The following is just one of many ways to do it:
const newData = data.map(({ key, title, ...datum }) => key === "3"
? { key, title: "newTitle", ...datum }
: {key, title, ...datum}
);
Generally you would map the previous array to the next array, checking the current key property for a match, and when found you copy also the element and update the title property, otherwise just pass through the current element.
const newData = data.map(el => el.key === '3' ? {
...el,
title: // the new title
} : el);
This is such a common pattern in React that you would extract this functionality into a function.
const updateTitleByKey = (key, title) => {
return data.map(el => el.key === key ? {
...el,
title
} : el);
};
Another example using dynamic keys:
const updatePropertyByKey = (key, name, value) => {
return data.map(el => el.key === key ? {
...el,
[name]: value
} : el);
};
const data = [
{
key: '1',
title: 'Title 1',
desc: 'Desc 1',
image: 'http://192.168.0.22:3000/build/photo_1621612104216_d747ced4-b313-4687-b9ac-ab5bcd78501d.jpg'
},
{
key: '2',
title: 'Title 2',
desc: 'Desc 2',
image: 'http://192.168.0.22:3000/build/photo_1621612230526_f49f2be8-6fd6-420d-b0b0-b39216418924.jpg'
},
{
key: '3',
title: 'Title 3',
desc: 'Desc 3',
image: 'http://192.168.0.22:3000/build/photo_1621612230526_f49f2be8-6fd6-420d-b0b0-b39216418924.jpg'
},
{
key: '4',
title: 'Title 4',
desc: 'Desc 4',
image: 'http://192.168.0.22:3000/build/photo_1621612104216_d747ced4-b313-4687-b9ac-ab5bcd78501d.jpg'
},
];
const updatePropertyByKey = (key, name, value) => {
return data.map(el => el.key === key ? {
...el,
[name]: value
} : el);
};
const newData = updatePropertyByKey('3', 'title', 'Title 3 New');
console.log(newData[2]);
Related
I have a react.js component:
import ChatBot from 'react-simple-chatbot';
<ChatBot
steps={[
{
id: '1',
message: 'What number I am thinking?',
trigger: '2',
},
{
id: '2',
options: [
{ value: 1, label: 'Number 1', trigger: '4' },
{ value: 2, label: 'Number 2', trigger: '3' },
{ value: 3, label: 'Number 3', trigger: '3' },
{ value: 4, label: 'Number 3', trigger: '3' },
{ value: 5, label: 'Number 3', trigger: '3' },
],
},
{
id: '3',
message: 'Wrong answer, try again.',
trigger: '2',
},
{
id: '4',
message: 'Awesome! You are a telepath!',
end: true,
},
]}
/>
After clicking on one of the options, i would like it not to be displayed again in the next step. I tried almost everything like state, filter() and lot of more to do that, and nothing works :'(.
ChatBot Documentation: https://lucasbassetti.com.br/react-simple-chatbot/#/docs/options
Please help :[
I'm sure if you're using ant design menu component you've got the same error:
Warning: [antd: Menu] children will be removed in next major version. Please use items instead.
the new way to make this is:
const items = [
{ label: 'item 1', key: 'item-1' },
{ label: 'item 2', key: 'item-2' },
{
label: 'sub menu',
key: 'submenu',
children: [{ label: 'item 3', key: 'submenu-item-1' }],
},
];
return <Menu items={items} />
and you can define your function and use it like this:
return <Menu onClick={onClick} selectedKeys={[current]} mode="horizontal" items={items} />;
how can i have different functions on my items?
i'll be glad if someone help me with this
in the old way i could easily define any functions i want on any items
Actually, we can add functions to the items array as well
const [current, setCurrent] = useState();
const func = () => {
setCurrent(e.key);
}
const func2 = () => {
setCurrent(e.key);
}
const items = [
{
label: 'item 1',
key: 'item-1'
onClick: func,
className: class1,
},
{
label: 'item 1',
key: 'item-1'
onClick: func2,
className: class2,
},,
{
label: 'sub menu',
key: 'submenu',
children: [{ label: 'item 3', key: 'submenu-item-1' }],
},
];
return <Menu selectedKeys={[current]} mode="horizontal" items={items} />;
I use react-bootstrap-table-next. And want to use a toggle button which hide or show rows with a certain value. But the problem is that the table content doesn't change.
import BootstrapTable from 'react-bootstrap-table-next';
const products = [
{id: 0, name: 'item 0', price: 4},
{id: 1, name: 'item 1', price: 5},
{id: 2, name: 'item 2', price: 3},
{id: 3, name: 'item 3', price: 5},
]
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name',
}, {
dataField: 'price',
text: 'Product Price',
}];
const handleClick = () => {
for (i=0; i> products.length; i++) {
if (products[i]["price"] === 5) {
products.slice(i, 1);
}
}
};
export default () => (
<div>
<button className="btn btn-lg btn-primary" onClick={ handleClick }>hide data </button>
<BootstrapTable keyField='id' data={ products } columns={ columns } />
</div>
);
The problem is that you are trying to update products, but on every re-render, it will reset to its initial value (Because it's defined outside the component's function). So, the value of products will always be the same.
One solution is to move products inside the component and create a state for it.
You can reshape your code like this:
import BootstrapTable from 'react-bootstrap-table-next';
import { useState } from 'react';
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name',
}, {
dataField: 'price',
text: 'Product Price',
}];
const MyComponent = () => {
const [products, setProducts] = useState([
{ id: 0, name: 'item 0', price: 4 },
{ id: 1, name: 'item 1', price: 5 },
{ id: 2, name: 'item 2', price: 3 },
{ id: 3, name: 'item 3', price: 5 },
]);
const handleClick = () => {
let temp = products;
for (i = 0; i > temp.length; i++) {
if (temp[i]["price"] === 5) {
temp.slice(i, 1);
}
};
setProducts(temp);
};
return (
< div >
<button className="btn btn-lg btn-primary" onClick={handleClick}>hide data </button>
<BootstrapTable keyField='id' data={products} columns={columns} />
</div >
)
};
export default MyComponent;
I'm setting up an array of list, and want to parse the value from JSON to that list
This is the array
const universityOptions = [
{ key: '1', text: 'Universtiy 1', value: 'Universtiy 1' },
{ key: '2', text: 'Universtiy 2', value: 'Universtiy 2' },
{ key: '3', text: 'Universtiy 3', value: 'Universtiy 3' },
{ key: '4', text: 'Universtiy 4', value: 'Universtiy 4' },
{ key: '5', text: 'Universtiy 5', value: 'Universtiy 5' },
{ key: '6', text: 'Universtiy 6', value: 'Universtiy 6' }
]
Below is the json
{"success":true,"data":[{"id":1,"name":"University 1"},{"id":2,"name":"University 2"},{"id":3,"name":"University 3"},{"id":4,"name":"University 4"},{"id":5,"name":"University 5"},{"id":6,"name":"University 6"}]}
and this is the method i tried so far, which i get the data but i only need the data.name (university name) and i'm stuck how to get it
componentDidMount() {
const univFetch = fetch('url')
// university_list state
univFetch.then(res => {
if( res.status === 200)
return res.json()
}).then( univJson => {
this.setState({
university_list: univJson.data
})
console.log(univJson.data);
})
}
Result
(6) [{…}, {…}, {…}, {…}, {…}, {…}]
0: {id: 1, name: "University 1"}
1: {id: 2, name: "University 2"}
2: {id: 3, name: "University 3"}
3: {id: 4, name: "University 4"}
4: {id: 5, name: "University 5"}
5: {id: 6, name: "University 6"}
length: 6
__proto__: Array(0)
I expect the output is an array like
const universityOptions = [
{ key: '1', text: 'Universtiy 1', value: 'Universtiy 1' },
{ key: '2', text: 'Universtiy 2', value: 'Universtiy 2' },
{ key: '3', text: 'Universtiy 3', value: 'Universtiy 3' },
{ key: '4', text: 'Universtiy 4', value: 'Universtiy 4' },
{ key: '5', text: 'Universtiy 5', value: 'Universtiy 5' },
{ key: '6', text: 'Universtiy 6', value: 'Universtiy 6' }
]
Thanks
Try it like this:
const newArray = json.data.map(elem => ({
key: elem.id.toString(),
text: elem.name,
value: elem.name
}));
Your componentDidMount() would end up being something like this:
componentDidMount() {
const univFetch = fetch('url')
univFetch.then(res => {
if( res.status === 200)
return res.json()
}).then( univJson => {
const universityList = univJson.data.map(elem => ({
key: elem.id.toString(),
text: elem.name,
value: elem.name
}));
this.setState({
university_list: universityList
})
})
}
Here's the Sandbox if you want to take a look at it. Hope it helps.
You need to iterate over your response and you can create desired output like this,
this.setState({
university_list : univJson.data.map(data => ({key:data.id,text:data.name,value:data.name}))
}, ()=>console.log(this.state.university_list))
Error is use forEach on univJson and create an array
componentDidMount() {
const univFetch = fetch('url')
// university_list state
univFetch.then(res => {
if( res.status === 200)
return res.json()
}).then( univJson => {
let univArray = [];
univJson.forEach((datum, index) => {
univArray.push({ key: datum.id, text: datum.name, value: datum.name});
})
this.setState({
university_list: univArray
})
console.log(univJson.data);
})
}
Why not perform an extra operation,
componentDidMount() {
const univFetch = fetch('url')
// university_list state
univFetch.then(res => {
if( res.status === 200)
return res.json()
}).then( univJson => {
var output = [];
for(var i=0 ;i<univJson.data;i++){
var obj = {key : univJson.data[i]["id"],
text : univJson.data[i]["name"],
value : univJson.data[i]["name"]
}
output.push(obj)
}
this.setState({
university_list: output
});
console.log(output);
})
}
I have 2 javascript arrays which are a, b and I want to remove the common elements from the array a.
Can you please help on this.
var a = [{
name: 'java',
id: '1'
},
{
name: 'php',
id: '2'
},
{
name: 'ruby',
id: '3'
},
{
name: 'phyton',
id: '4'
}
];
var b = [{
name: 'java',
id: '1'
},
{
name: 'php',
id: '2'
}
];
It's basically a simple filter operation. I'd take the ids from b into an array, then filter by those elements
var a = [{
name: 'java',
id: '1'
},
{
name: 'php',
id: '2'
},
{
name: 'ruby',
id: '3'
},
{
name: 'phyton',
id: '4'
}
];
var b = [{
name: 'java',
id: '1'
},
{
name: 'php',
id: '2'
}
];
const exists = b.map(e => e.id);
const res = a.filter(e => !exists.includes(e.id));
console.log(res);