[英]How do I loop through array with js objects and make conditional replacement of values
New to the programming game, I have an array with a small list of js-objects containing responses for personality test questions.编程游戏的新手,我有一个数组,其中包含一小部分 js 对象,其中包含对性格测试问题的回答。
Each response is related to a personality factor, has a question, describes wether this correlates positively or negatively with the factor, and finally the response on a scale from 1-5.每个回答都与一个人格因素有关,有一个问题,描述了这与该因素是正相关还是负相关,最后是 1-5 等级的回答。
I need to loop through the array and whenever the key positive has a value of 0, I want to flip the response so that a 1 = 5, 2 = 4, 3 = 3, 4 = 2, 5 = 1.我需要遍历数组,每当正键的值为 0 时,我想翻转响应,以便 1 = 5、2 = 4、3 = 3、4 = 2、5 = 1。
const response = [
{
factor: "conscientinous",
question: "Prepare for things in advance",
positiv: 1,
rating: 3,
},
{
factor: "conscientious",
question: "Let things get into a mess",
positiv: 0,
rating: 1,
},
];
I am trying to do this within a functional paradigm and was thinking.map might be a way forward.我正在尝试在功能范例中执行此操作并且正在思考。map 可能是一种前进的方式。
Iterate the array with Array.map()
, and if positiv
is 0, return a new object by spreading the original object, and getting the new rating
by substracting the old rating from 6:使用
Array.map()
迭代数组,如果positiv
为 0,则通过展开原始 object 返回新的 object,并通过从 6 中减去旧评级获得新rating
:
const response = [{"factor":"conscientinous","question":"Prepare for things in advance","positiv":1,"rating":3},{"factor":"conscientious","question":"Let things get into a mess","positiv":0,"rating":1}]; const result = response.map(o => o.positive? o: {...o, rating: 6 - o.rating }) console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.