gpt4 book ai didi

javascript - 从对象中删除标识符

转载 作者:行者123 更新时间:2023-12-01 01:10:05 25 4
gpt4 key购买 nike

我有一个带有标识符的对象:

const cities = {
"0": {
"city": "Bielsko-Biała",
"country": "PL",
},
"1": {
"city": "Kielce",
"country": "PL",
},
"2": {
"city": "Kłodzko",
"country": "PL",
}
}

我想要的是删除 0、1、2 等以获得此格式:

const cities = [
{
"city": "Bielsko-Biała",
"country": "PL",
},
{
"city": "Kielce",
"country": "PL",
},
{
"city": "Kłodzko",
"country": "PL",
}
]

这对我来说是必要的,因为我想为每个城市添加描述,但由于这种格式,我无法在该对象中进行映射。

我必须在 React 中做类似的事情,我认为这是一个非常糟糕的编写代码:

const cities = [];

countries.map(el => {
cities.push(el.city)
})

let updatedCountries = countries;

cities.forEach((city) => {
axios.get(`https://en.wikipedia.org/api/rest_v1/page/summary/${city}`)
.then(response => {
for (let property in updatedCountries) {
if (updatedCountries.hasOwnProperty(property)) {
if (updatedCountries[property].city === city) {
updatedCountries[property]['description'] = response.data.description
}
}
}
})
})

this.setState({
countries: updatedCountries
})

最佳答案

您可以使用Object.values()

The Object.values() method returns an array of a given object's own enumerable property values,

const cities = {
"0": {
"city": "Bielsko-Biała",
"country": "PL",
},
"1": {
"city": "Kielce",
"country": "PL",
},
"2": {
"city": "Kłodzko",
"country": "PL",
}
}
let values = Object.values(cities);
console.log(values);

关于javascript - 从对象中删除标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55231966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com