【发布时间】:2018-12-13 15:22:10
【问题描述】:
我有一个像 ["Asthma", "Allergy", "Sports and Fitness"] 这样的数组,我需要将该数组转换为键值对字符串 - 如下所示:
prop1: Asthma prop1: Allergy prop1: Sports and Fitness prop2: Asthma, prop2: Allergy prop2: Sports and Fitness
使用Array.Proptotype.Reduce() 可以做到这一点吗?
var propertyObjectRefinable = "";
jQuery("p[data-action='related-articles']>a span.media-content")
.map(function() {
return jQuery.trim($(this).text());
}).get().forEach(function(item){
propertyObjectRefinable += "RefinableString15:" + item + " " + "RefinableString16:" + item + " ";
});
给了我这样的东西,我不喜欢,因为它不按顺序
RefinableString15:Sports and Fitness RefinableString16:Sports and Fitness RefinableString15:Allergy RefinableString16:Allergy RefinableString15:Asthma RefinableString16:Asthma "
【问题讨论】:
-
使用 .reduce 有什么相关的理由吗?
-
并非如此。我只是从积累的角度思考
-
好吧。使用
map和reduce你可以想出这样的东西,作为起点:jsfiddle.net/briosheje/3r805z6g/3。仅以它为例(尽管它确实接近理想的解决方案),我在休息时想出了这个。
标签: javascript arrays dictionary reduce