从一个JavaScript对象获取元素,然后保存到另一个

时间:2020-07-06 11:03:04

标签: javascript

我想从一个javascript对象中获取一个元素,然后保存到另一个中。

我的对象看起来像这样:

let obj = {
  countries: [{
    'Country name': "Russia",
    Flag: "RU",
    Population: 146774178
  }, {
    'Country name': "Turkey",
    Flag: "TR",
    Population: 83154997
  }]
};

我的功能只能提醒特定的项目:

function custom() {
  for (var key in obj.countries) {
    var countryn = obj.countries[key]['Country name'];
    if(countryn = "Turkey") {
      alert(countryn);
    }
}}

在此函数中,如果我在对象中找到一个国家/地区,我希望将整个元素保存并保存到这样的新对象中:

{
  "countries": [
    {
      "Country name": "Turkey",
      "Flag": "TR",
      "Population": 83154997
    }
  ]
}

我该如何实现?

3 个答案:

答案 0 :(得分:0)

您可以声明一个名称为filteredCountries的空数组,并将所需的country对象压入filteredCountries数组中。

const filteredCountries = [];

function custom() {
  for (var key in obj.countries) {
    var countryn = obj.countries[key]['Country name'];
    if(countryn == "Turkey") {
       filteredCountries.push(obj.countries[key]);
    }
}}

或者,您也可以使用array.filterreference)方法来简化代码:

const filteredCountries = obj.countries.filter(country => country['Country Name'] === 'Turkey'));

答案 1 :(得分:0)

有多种方法可以实现此目的。一种方法是过滤现有数组。

const countryData = [{
  name: "Russia",
  flag: "RU"
}, {
  name: "Turkey",
  flag: "TR"
}];

function custom(countryData) {
  return countryData.filter(country => country.name === "Turkey");
}

const result = custom(countryData);
console.log(result);

答案 2 :(得分:0)

您要比较的第一件事是if中的错误条件。应该有==,而不是=之类的if(countryn == "Turkey")

要获得所需的结果,请在函数顶部声明数组。在if(countryn == "Turkey")内部将匹配的对象添加到数组。可以通过obj.countries[key]获取对象。

或者您可以简单地使用filter中的custom2作为return obj.countries.filter(x => x['Country name'] == "Turkey");

let obj = {
  countries: [{
    'Country name': "Russia",
    Flag: "RU",
    Population: 146774178
  }, {
    'Country name': "Turkey",
    Flag: "TR",
    Population: 83154997
  }]
};

function custom() {
  let customCountry = [];
  for (var key in obj.countries) {
    var countryn = obj.countries[key]['Country name'];
    if (countryn == "Turkey") {
      customCountry.push(obj.countries[key]);
    }
  }
  return { countries: customCountry };
}

function custom2() {
  let countries = obj.countries.filter(x => x['Country name'] == "Turkey");
  return { countries: countries }; 
}

console.log(custom(obj));
console.log(custom2(obj));