Home > other >  How can I iterate over an object that I don't know it's keys?
How can I iterate over an object that I don't know it's keys?

Time:03-04

I get something like this from the server:

{
  "2021-10-13": {
    "1. open": "141.2350",
    "2. high": "141.4000",
    "3. low": "139.2000",
    "4. close": "140.9100",
    "5. volume": "78762721"
  },
  "2021-10-12": {
    "1. open": "143.2300",
    "2. high": "143.2500",
    "3. low": "141.0401",
    "4. close": "141.5100",
    "5. volume": "73035859"
  },
  "2021-10-11": {
    "1. open": "142.2700",
    "2. high": "144.8100",
    "3. low": "141.8100",
    "4. close": "142.8100",
    "5. volume": "64452219"
  }
}

The key values may vary for different requests. How can I iterate over an object with unknown keys?

For example I want to write the second and third nested objects(stocks) inside the database but I don't know how should I specify them?

CodePudding user response:

Does this help?

type Keys = {
  "1. open": string;
  "2. high": string;
  "3. low": string;
  "4. close": string;
  "5. volume": string;
}
type B = {[Prop in keyof Keys]: Keys[Prop]}
type A = { [key: string]: B}
const result: A = {
  "2021-10-13": {
    "1. open": "141.2350",
    "2. high": "141.4000",
    "3. low": "139.2000",
    "4. close": "140.9100",
    "5. volume": "78762721"
  },
  "2021-10-12": {
    "1. open": "143.2300",
    "2. high": "143.2500",
    "3. low": "141.0401",
    "4. close": "141.5100",
    "5. volume": "73035859"
  },
  "2021-10-11": {
    "1. open": "142.2700",
    "2. high": "144.8100",
    "3. low": "141.8100",
    "4. close": "142.8100",
    "5. volume": "64452219"
  }
};

CodePudding user response:

Here's an approach for parsing the data you're receiving and sorting it by newest date first:

TS Playground

const rawSummaryKeys = ['1. open', '2. high', '3. low', '4. close', '5. volume'] as const;
type RawSummaryKey = typeof rawSummaryKeys[number];

const parsedSummaryKeys = ['open', 'high', 'low', 'close', 'volume'] as const;
type ParsedSummaryKey = typeof parsedSummaryKeys[number];

const rawToParsedSummaryKeyMapping: Record<RawSummaryKey, ParsedSummaryKey> = {
  '1. open': 'open',
  '2. high': 'high',
  '3. low': 'low',
  '4. close': 'close',
  '5. volume': 'volume',
};

/** Values are parsable as numbers */
type RawSummary = Record<RawSummaryKey, string>;

/** Keys are dates in format: YYYY-MM-DD */
type DailyRawSummaries = Record<string, RawSummary>;

type ParsedSummary = Record<ParsedSummaryKey, number>;

function parseRawSummary (summary: RawSummary): ParsedSummary {
  const parsed = {} as ParsedSummary;
  for (const key of rawSummaryKeys) {
    // If the "volume" number ever exceeds Number.MAX_SAFE_INTEGER,
    // then you can switch to using BigInts
    parsed[rawToParsedSummaryKeyMapping[key]] = Number(summary[key]);
  }
  return parsed;
}

type DailySummaryEntrry = [date: string, summary: ParsedSummary];

function parseDailySummaries (summaries: DailyRawSummaries): DailySummaryEntrry[] {
  const entries: DailySummaryEntrry[] = [];

  for (const date in summaries) {
    const rawSummary = summaries[date];
    if (!rawSummary) continue;
    entries.push([date, parseRawSummary(rawSummary)]);
  }

  return entries.sort().reverse(); // sort by newest date first
}

function main () {
  const json = `{"2021-10-13":{"1. open":"141.2350","2. high":"141.4000","3. low":"139.2000","4. close":"140.9100","5. volume":"78762721"},"2021-10-12":{"1. open":"143.2300","2. high":"143.2500","3. low":"141.0401","4. close":"141.5100","5. volume":"73035859"},"2021-10-11":{"1. open":"142.2700","2. high":"144.8100","3. low":"141.8100","4. close":"142.8100","5. volume":"64452219"}}`;
  const raw: DailyRawSummaries = JSON.parse(json);

  const parsed = parseDailySummaries(raw);

  for (const [date, summary] of parsed) {
    console.log(date, summary);
  }
}

main();

Transpiled JS from TS playground:

const rawSummaryKeys = ['1. open', '2. high', '3. low', '4. close', '5. volume'];
const parsedSummaryKeys = ['open', 'high', 'low', 'close', 'volume'];
const rawToParsedSummaryKeyMapping = {
    '1. open': 'open',
    '2. high': 'high',
    '3. low': 'low',
    '4. close': 'close',
    '5. volume': 'volume',
};
function parseRawSummary(summary) {
    const parsed = {};
    for (const key of rawSummaryKeys) {
        // If the "volume" number ever exceeds Number.MAX_SAFE_INTEGER,
        // then you can switch to using BigInts
        parsed[rawToParsedSummaryKeyMapping[key]] = Number(summary[key]);
    }
    return parsed;
}
function parseDailySummaries(summaries) {
    const entries = [];
    for (const date in summaries) {
        const rawSummary = summaries[date];
        if (!rawSummary)
            continue;
        entries.push([date, parseRawSummary(rawSummary)]);
    }
    return entries.sort().reverse(); // sort by newest date first
}
function main() {
    const json = `{"2021-10-13":{"1. open":"141.2350","2. high":"141.4000","3. low":"139.2000","4. close":"140.9100","5. volume":"78762721"},"2021-10-12":{"1. open":"143.2300","2. high":"143.2500","3. low":"141.0401","4. close":"141.5100","5. volume":"73035859"},"2021-10-11":{"1. open":"142.2700","2. high":"144.8100","3. low":"141.8100","4. close":"142.8100","5. volume":"64452219"}}`;
    const raw = JSON.parse(json);
    const parsed = parseDailySummaries(raw);
    for (const [date, summary] of parsed) {
        console.log(date, summary);
    }
}
main();

  • Related