我真的被困在这里。请帮忙!
我有一个像这样的数组:
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”: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:{面积:{英亩:“ 249,561.00”,square_km:“ 1,009.9”}坐标:{纬度:34.01,经度:-119.42} id:“ park_channel-islands” ...
我想这行得通,您需要创建一个数组并将其与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] })
尝试一下
当我得到它时,您只希望拥有原始对象的2个属性(title
和coordinates
),并摆脱其他属性。
尝试下面的代码
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)