簡體   English   中英

如何從 typescript 中的數組中獲取動態鍵值

[英]How do I get dynamic key values from an array in typescript

const jsonData = {
  a: '123',
  b: '456',
  c: '789'
}

type needArr = string[]


function test(obj: any, array: needArr): {
  [props: T in needArr]: string
} {
  const newObj = {};
  for (let item of array) {
    newObj[ item ] = obj[ item ] || '';
  }
  return newObj;
}

預計

const params1 = test(json, ['a']); // params1 從 jsonData 中獲取 key a

const params2 = test(json, ['a', 'b']); // params2 從 jsonData 中獲取類型鍵 a、b

但是現在語法錯誤,應該怎么做才能讓程序正常運行

一個快速打字解決方案,使這項工作。

export type ValuesOf<T extends any[]>= Record<T[number], unknown>;
function test(obj: Record<string, unknown>, array: (keyof JSONDataType)[]): ValuesOf<typeof array> {
  const newObj = {} as Record<string, unknown>;
  for (let item of array) {
    newObj[ item ] = obj[ item ] || '';
  }
  return newObj;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM