我真的被困在这里。请帮忙!
我有一个像这样的数组:
0:{
area: {acres: "249,561.00", square_km: "1,009.9"}
coordinates: {latitude: 34.01, longitude: -119.42}
id: "park_channel-islands"
title: "Channel Islands"
visitors: "364,807}
1: {area: {…}, coordinates: {…}, date_established_readable...
2: .....
3: ....
这是我在构造函数this.state ={coodLabell:[]}
中的状态
我想通过在数组中创建字段坐标和字段标题的对象来填充数组协调器。
例如:在索引0中。我想创建对象{“ title”:标题,“ cood”:坐标“,并将其推入构造函数中的空数组协调器中。
这是我尝试过的方法,但我总是找回空数组
array.forEach((element) => {
const title = element.title
const cood = element.coordinates
const newData = {"title": title, "cood": cood}
this.setState({coodLabell:[...this.state.coodLabell,...newData]})
如果您能给我一些提示,我将不胜感激。谢谢
答案 0 :(得分:0)
我想这行得通,您需要创建一个数组并将其与foreach之后的当前状态结合起来。
let newArray = []
array.forEach((element) => {
const title = element.title
const cood = element.coordinates
const newData = { "title": title, "cood": cood };
newArray.push(newData);
})
this.setState({ coodLabell: [...this.state.coodLabell, ...newArray] })
答案 1 :(得分:0)
尝试一下
const newData = {"title": title, "cood": cood}
let Data = this.state.coodLabell.push(newData)
this.setState({coodLabell:Data})
答案 2 :(得分:0)
当我得到它时,您只想拥有原始对象的2个属性(title
和coordinates
),并摆脱其他属性。
在这种情况下,您必须像这样映射数组:
const data = [
{
area: { acres: '249,561.00', square_km: '1,009.9' },
coordinates: { latitude: 34.01, longitude: -119.42 },
id: 'park_channel-islands',
title: 'Channel Islands',
visitors: '364,807',
},
{
area: { acres: '249,561.00', square_km: '1,009.9' },
coordinates: { latitude: 20.01, longitude: -100.42 },
id: 'park_channel-islands',
title: 'Abc',
visitors: '364,807',
},
{
area: { acres: '249,561.00', square_km: '1,009.9' },
coordinates: { latitude: 10.01, longitude: -50.42 },
id: 'park_channel-islands',
title: 'Xyz',
visitors: '364,807',
},
];
const filteredData = data.map(({title, coordinates}) => ({title, coordinates}))
console.log({filteredData})
// and here you can
// this.setState({ anything: filteredData })
答案 3 :(得分:0)
尝试下面的代码
const coodLabell = Object.values(yourData).map(element => {
return {
"title": element.title,
"cood": element.coordinates
}
});
this.setState({ coodLabell })
答案 4 :(得分:0)
const [coodLabell, setCoodLabell] = useState({});
const array = [
{
area: {acres: "249,561.00", square_km: "1,009.9"}
coordinates: {latitude: 34.01, longitude: -119.42}
id: "park_channel-islands"
title: "Channel Islands"
visitors: "364,807
},
{....},
{....},
{....},
];
let coodLabell = array.map(item => {
return {
title: item.title,
cood: item.coordinates
}
})
setCoodLabell(coodLabell)