将javascript数组放入键值空间分隔的字符串

时间:2018-12-13 15:22:11

标签: javascript arrays dictionary reduce

我有一个类似["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 "

2 个答案:

答案 0 :(得分:1)

您可以使用地图:

["Asthma", "Allergy", "Sports and Fitness"].map((item) => {
    return `prop1: ${item}`;
}).toString();

或更易于理解和使用的

let arr = ["Asthma", "Allergy", "Sports and Fitness"];
let newArr = arr.map((item) => {
    return `prop1: ${item}`;
});
console.log(newArr.toString());

输出:

"prop1: Asthma,prop1: Allergy,prop1: Sports and Fitness"

地图将为您返回一个包含新项目的新数组。

答案 1 :(得分:1)

您可以在map()join()的帮助下完成此操作

let arr =["Asthma", "Allergy", "Sports and Fitness"];
let op = arr.map(e=>`prop1: ${e}`).join(' ');
console.log(op);

如果您想要多个物业

let arr =["Asthma", "Allergy", "Sports and Fitness"];
let op = arr.reduce((e,a)=>{
 e[0].push(`prop1: ${a}`);
 e[1].push(`prop2: ${a}`);
 return e;
 },[[],[]]);
 let final = op.map(e=> e.join(' ')).join(' ');
console.log(final);