简体   繁体   English

根据JSON文件中的键值对转换JavaScript数组。

[英]Convert JavaScript array based on key value pairs from a JSON file.

I am trying to create a system to flag inappropriate comments for my app. 我正在尝试创建一个系统来标记对我的应用程序不适当的评论。

I have a system to convert the whole comment into an array of strings, however I would like to create a JavaScript function to convert all of these array items to a number value based on key value pairs from JSON. 我有一个将整个注释转换为字符串数组的系统,但是我想创建一个JavaScript函数,根据来自JSON的键值对将所有这些数组项转换为数字值。 If a key is not found that matches the word it should be replaced by a 0. 如果找不到与单词匹配的键,则应将其替换为0。

All values in the final array will be added together to get a comment score. 最终数组中的所有值将加在一起以获得评论分数。

Here is an example starting array: 这是一个示例起始数组:

["Bad", "reallyBad", "Good", "Neutral", "Good"]

I would like to compare this to a JSON key: value object such as: 我想将此与JSON键:value对象进行比较,例如:

{
    "reallyBad": -10,
    "Bad": -5,
    "Good": 5,
    "reallyGood": 10
}

Based on the key value pairs the new array should be this: 基于键值对,新数组应为:

[-5, -10, 5, 0, 5]

Does anyone know a good place to start when converting strings based on a key: value pair? 在基于键:值对转换字符串时,有人知道入门的好地方吗?

Any help would be massively appreciated. 任何帮助将不胜感激。

Just map the values of the object, or take a default value for Neutral . 只需映射对象的值,或为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); 

You can use .map() on an array to perform a function on each item in the array and return something for that. 您可以在数组上使用.map()对数组中的每个项目执行功能,并为此返回某些内容。 So, take each string in your array and use that as the key to get the value from your ratings object. 因此,将数组中的每个字符串用作键,以从评级对象中获取值。

 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); 

you can simply use Array.map() 您可以简单地使用Array.map()

Try the following: 请尝试以下操作:

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM