从对象中删除标识符

时间:2019-03-19 00:25:39

标签: javascript object

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

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

1 个答案:

答案 0 :(得分:2)

您可以使用Object.values()

  

Object.values()方法返回给定对象自己的可枚举属性值的array

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