[英]Return a specific variable of a JSON body in REQUEST nodejs
我有这段代码对我来说效果很好,它为我带来了 JSON 格式的主体,但我不想要整个主体,我想要同一主体的特定变量,这就是代码。
var request = require("request"); var options = { method: 'GET', url: 'https://xxx', qs: {stats: 'true', events: 'true'}, headers: { 'x-rapidapi-host': 'xx', 'x-rapidapi-key': 'xxx' } }; request(options, function (error, response, body) { if (error) throw new Error(error); console.log(body); **console.log('HOME NOMBRE: ' + body.results.id);** });
这给了我一个像这样的 JSON 文件:
{"results":[{"id":1, "idSeason":949, "seasonName":"2020", "idHome":2069, "homeName":"MyHome", "idAway":207 ....}
我希望能够实现一些专门为我带来变量的方法,例如 homeName,以便只能使用它!
我希望我解释得很好,我期待你的帮助!
如果您的 API 返回一个对象数组,而您只需要一个对象属性的值数组,请使用 map...
let results = [{ "id": 1, "idSeason": 949, "seasonName": "2020", "idHome": 2069, "homeName": "MyHome", "idAway": 207 }, { "id": 2, "idSeason": 950, "seasonName": "2021", "idHome": 2070, "homeName": "MyHome2", "idAway": 208 }] // native console.log(results.map(e => e.homeName)) // or using underscore console.log(_.pluck(results, 'homeName')) // or a smaller object console.log(results.map(e => _.pick(e, 'id', 'seasonName', 'idAway')))
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
我认为更好的方法是使用 ES6 地图。
如果您使用对象数组
const results = [{
"id": 1,
"idSeason": 949,
"seasonName": "2020",
"idHome": 2069,
"homeName": "MyHome",
"idAway": 207
}, {
"id": 2,
"idSeason": "x",
"seasonName": "x",
"idHome": "x",
"homeName": "MyHomex",
"idAway": "x"
}]
const formattedRes = results.map(singleObject =>{
// Here redeclare the object you want, here i want to return id,seasonName and homeName
return {
"id": singleObject.id,
"seasonName": singleObject.seasonName,
"homeName": singleObject.seasonName,
}
});
console.log(formattedRes);
结果将是
[ { id: 1, seasonName: '2020', homeName: '2020' },
{ id: 2, seasonName: 'x', homeName: 'x' } ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.