在 JavaScript 中顯示物件條目中的子串是否可行?


可以的,你可以將 Object.fromEntries() 和 substr() 一起使用。在 substr() 中,指定子字串開始的索引和長度。

示例

const originalString = {
   "John 21 2010" :1010,
   "John 24 2012" :1011,
   "John 22 2014" :1012,
   "John 22 2016" :1013,
}
const result = Object.fromEntries(Object.entries(originalString).
map(([k, objectValue])=>
[k.substr(0, k.length-5), objectValue]));
console.log(result)

要執行以上程式,你需要使用以下命令 −

node fileName.js.

此處,我的檔名為 demo41.js。

輸出

這將產生以下輸出 −

PS C:\Users\Amit\JavaScript-code> node demo41.js
{ 'John 21': 1010, 'John 24': 1011, 'John 22': 1013 }

更新時間: 01-9 月-2020

253 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.