如何获取特定JSON数据项?提取NIFTY 50指数数据的方法
Hey there! I see you're working with the indian-stock-exchange API and need to pull just the NIFTY 50 data from the indices array. Let's break this down and fix your code.
The Problem
Your current code fetches all indices and logs the entire array. From your sample output, the NIFTY 50 is the first item in the response.data array, but we can also make this more robust in case the API ever changes the order of indices.
Solution 1: Directly Access the First Array Item
Since NIFTY 50 is the first entry in the returned array, you can simply use index [0] to grab it:
const api = require('indian-stock-exchange'); const nse = api.NSE; nse.getIndices().then(function(response) { // Grab the first item (NIFTY 50) from the data array const nifty50Data = response.data[0]; console.log('NIFTY 50 Data:', nifty50Data); });
Solution 2: Robust Lookup by Index Name (Recommended)
If you want to avoid relying on the array order (in case the API updates and changes the position of NIFTY 50), use the find() method to search for the index by its indexName:
const api = require('indian-stock-exchange'); const nse = api.NSE; nse.getIndices().then(function(response) { // Find the index where indexName matches 'NIFTY 50' const nifty50Data = response.data.find(index => index.indexName === 'NIFTY 50'); if (nifty50Data) { console.log('NIFTY 50 Data:', nifty50Data); } else { console.log('NIFTY 50 data not found in response'); } });
What This Does
- Solution 1 is quick and works perfectly for your current API response structure.
- Solution 2 is more future-proof: it will always find NIFTY 50 regardless of its position in the array, and adds a safety check to handle cases where the data might be missing.
Either approach will get you the specific NIFTY 50 data you need!
内容的提问来源于stack exchange,提问作者Ashish Bajaj

