简体   繁体   English

在 REQUEST nodejs 中返回 JSON 正文的特定变量

[英]Return a specific variable of a JSON body in REQUEST nodejs

I have this code which works perfectly well for me, it brings me the body in JSON, but I don't want the whole body, I want a specific variable of that same body, this is the code.我有这段代码对我来说效果很好,它为我带来了 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);** });

this gives me a JSON file like this:这给了我一个像这样的 JSON 文件:

 {"results":[{"id":1, "idSeason":949, "seasonName":"2020", "idHome":2069, "homeName":"MyHome", "idAway":207 ....}

I would like to be able to realize some method that brings me exclusively the variable, for example, homeName, to be able to work only with it!我希望能够实现一些专门为我带来变量的方法,例如 homeName,以便只能使用它!

I hope I am explaining well, I expect your help!我希望我解释得很好,我期待你的帮助!

If your API returns an array of objects, and you just want an array of values for one of the objects' properties, use map...如果您的 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>

I think better way to do this is just use ES6 map.我认为更好的方法是使用 ES6 地图。

if you use array of objects如果您使用对象数组

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

result will be结果将是

[ { id: 1, seasonName: '2020', homeName: '2020' },
  { id: 2, seasonName: 'x', homeName: 'x' } ]

for more map - MDN Doc更多地图 - MDN Doc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM