从JSON中的不同对象中的相同键中选择值

时间:2017-01-18 00:28:57

标签: javascript arrays json object

我有一个像这样的JSON文件;

"forecastday": [
  {
    "date": "01-18",
    "day": {
      "maxtempc": 12.6,
      "maxtempf": 54.7,
      "mintempc": 6.1,
      "mintempf": 43.0,
      "condition": {
        "text": "Sunny",
        "icon": "a"
      }
    }
  },
  {
    "date": "01-19",
    "day": {
      "maxtempc": 14.6,
      "maxtempf": 40.3,
      "mintempc": 3.1,
      "mintempf": 41.0,
      "condition": {
        "text": "Cloudy",
        "icon": "a"
      }
    }
  },
  {
    "date": "01-20",
    "day": {
      "maxtempc": 11.1,
      "maxtempf": 50.2,
      "mintempc": 7.2,
      "mintempf": 39.0,
      "condition": {
        "text": "Rainy",
        "icon": "a"
      }
    }
  }
]

我需要从不同日期的maxtempc,maxtempf,mintempc,mintempf,icon中选择值并放入不同的div中。我在等你的帮助。

4 个答案:

答案 0 :(得分:2)

var days = forecastdayArray.map(i => i.day) // array of day objects with the properties you needed

//accessing the properties
days.forEach(function(item) {
console.log(item.maxtempc)
console.log(item.maxtempf)
console.log(item.mintempc)
console.log(item.mintempf)
console.log(item.condition.icon)
});

答案 1 :(得分:1)

data.forecastday.map(x => x.day.maxtempc)

答案 2 :(得分:0)

我认为你可能需要解析"你的json之前可以使用它...这是使用你的数据的基本方法。我希望这会有所帮助。

var initialarrays = JSON.parse(`[
  {
    "date": "01-18",
    "day": {
      "maxtempc": 12.6,
      "maxtempf": 54.7,
      "mintempc": 6.1,
      "mintempf": 43.0,
      "condition": {
        "text": "Sunny",
        "icon": "a"
      }
    }
  },
  {
    "date": "01-19",
    "day": {
      "maxtempc": 14.6,
      "maxtempf": 40.3,
      "mintempc": 3.1,
      "mintempf": 41.0,
      "condition": {
        "text": "Cloudy",
        "icon": "a"
      }
    }
  },
  {
    "date": "01-20",
    "day": {
      "maxtempc": 11.1,
      "maxtempf": 50.2,
      "mintempc": 7.2,
      "mintempf": 39.0,
      "condition": {
        "text": "Rainy",
        "icon": "a"
      }
    }
  }
]`);

var mynewarrs = initialarrays.map(function(initialarray){
    return initialarray.day;
})

var finalarrays = mynewarrs.map(function(mynewarr){
  return mynewarr.maxtempc;
});

console.log(mynewarrs);

答案 3 :(得分:0)

如果我真的知道你想要完成的是你正在寻找的代码:

var date = initialarrays[i].date;//i refers to index and this is how you extract the date value which correspond to the index you entred.
var maxtempc = initialarrays[i].day.maxtempc;//this line extract the maxtempc value, and this one for the rest of them also;
var icon = initialarrays[i].day.condition.icon;// this one extract the icon value;

我希望我的示例清晰明确,如果你需要获取所有数据,你可以使用动态'i'循环遍历initialarrays并将每个结果附加到其各自的div。

这就是全部,如果我错过任何事情就让我知道