簡體   English   中英

我有一個對象數組和一個對象,我想遍歷對象,同時將對象值與數組中的值匹配

[英]I have an array of objects and an object I want to loop through an object while matching object values with the values in the array

我想遍歷一個具有十個答案作為其值的變量,這十個值必須與對象上的值匹配,以便我可以獲取與Answers變量上的值相關聯的字符串。

var可能的值= [{value1:'完全同意',weight:5},{value1:'高度同意',weight:4},{value1:'Partialy Agree',weight:3},{value1:'高度不同意' ,weight:2},{value1:'完全不同意',weight:1}];

        var answers = [1, 3, 1, 4, 2, 2, 5, 1, 2, 5];
        var result = '';

        /*Loop through answers variable and possibleValues array of objects
         find match between answers value and possibleValues weight
         then if there is a match save value1's value in the result variable*/

        for(i=0;i<answers.length;i++){
            if(possibleValues[i].weight===answers[i].value){
                result = possibleValues[i].value1;
            }
            alert(result);
        }

我想循環遍歷答案變量和對象的valuesvalues數組,找到答案值和valuesvalues權重之間的匹配,然后在結果變量中是否存在匹配保存value1的值。

所有結果= ['完全不同意','部分同意','完全不同意','高度同意','高度不同意','高度不同意','完全同意','完全同意'不同意”,“高度不同意”,“完全同意”];

嘗試這個..

 var possibleValues = [ {value1: "Completly Agree", weight: 5}, {value1: "Highly Agree", weight: 4}, {value1: "Partialy Agree", weight: 3}, {value1: "Highly Disagree", weight: 2}, {value1: "Completly Disagree", weight: 1} ]; var answers = [1, 3, 1, 4, 2, 2, 5, 1, 2, 5]; var result = []; for (var i = 0; i < answers.length; i++) { possibleValues.forEach(function (element) { if (answers[i] == element.weight) { result[i] = element.value1; } }); } console.log(result); 

您可以將所有值和weight作為鍵的Map

對於所需的結果,請通過從映射中獲取值來映射權重。

 var possibleValues = [{ value1: 'Completly Agree', weight: 5 }, { value1: 'Highly Agree', weight: 4 }, { value1: 'Partialy Agree', weight: 3 }, { value1: 'Highly Disagree', weight: 2 }, { value1: 'Completly Disagree', weight: 1 }], answers = [1, 3, 1, 4, 2, 2, 5, 1, 2, 5], result = answers.map( Map.prototype.get, possibleValues.reduce((m, { value1, weight }) => m.set(weight, value1), new Map) ); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

只需使用帶有值的對象,然后只需使用對象的值即可將數組map()覆蓋:

 var values = { 5: "Completely Agree", 4: "Highly Agree", 3: "Partially Agree", 2: "Highly Disagree", 1: "Completely Disagree" }; var answers = [1, 3, 1, 4, 2, 2, 5, 1, 2, 5]; var result = answers.map(e => values[e]); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

暫無
暫無

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

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