简体   繁体   中英

javascript array into key value space separated string

I have an array like this ["Asthma", "Allergy", "Sports and Fitness"] and I need to convert that array to a string of key value pair - something like below:

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

Is this possible to do this using 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 + " ";     
});

gives me something like this, which I don't like because it is not in order

RefinableString15:Sports and Fitness RefinableString16:Sports and Fitness RefinableString15:Allergy RefinableString16:Allergy RefinableString15:Asthma RefinableString16:Asthma "

You could use map:

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

or more humanly readable & cleaner:

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

Output:

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

Map will return you a new array containing the new items.

You can do it like this with help of map() and join()

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

In case you want more than one property

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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