[英]convert JSON array of key value pairs to JSON Array of strings in Javascript
[英]Convert JavaScript array based on key value pairs from a JSON file.
我正在嘗試創建一個系統來標記對我的應用程序不適當的評論。
我有一個將整個注釋轉換為字符串數組的系統,但是我想創建一個JavaScript函數,根據來自JSON的鍵值對將所有這些數組項轉換為數字值。 如果找不到與單詞匹配的鍵,則應將其替換為0。
最終數組中的所有值將加在一起以獲得評論分數。
這是一個示例起始數組:
["Bad", "reallyBad", "Good", "Neutral", "Good"]
我想將此與JSON鍵:value對象進行比較,例如:
{
"reallyBad": -10,
"Bad": -5,
"Good": 5,
"reallyGood": 10
}
基於鍵值對,新數組應為:
[-5, -10, 5, 0, 5]
在基於鍵:值對轉換字符串時,有人知道入門的好地方嗎?
任何幫助將不勝感激。
只需映射對象的值,或為Neutral
取默認值即可。
var array = ["Bad", "reallyBad", "Good", "Neutral", "Good"], weights = { reallyBad: -10, Bad: -5, Good: 5, reallyGood: 10 }, result = array.map(w => weights[w] || 0); console.log(result);
您可以在數組上使用.map()
對數組中的每個項目執行功能,並為此返回某些內容。 因此,將數組中的每個字符串用作鍵,以從評級對象中獲取值。
const array = ["Bad", "reallyBad", "Good", "Neutral", "Good"]; const ratings = { "reallyBad": -10, "Bad": -5, "Good": 5, "reallyGood": 10 }; const ratingsArray = array.map(item => ratings[item] || 0); console.log(ratingsArray);
您可以簡單地使用Array.map()
請嘗試以下操作:
var arr = ["Bad", "reallyBad", "Good", "Neutral", "Good"]; var obj = { "reallyBad": -10, "Bad": -5, "Good": 5, "reallyGood": 10 }; var result= arr.map((a)=> obj[a] || 0); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.