【问题标题】:javascript array into key value space separated stringjavascript数组到键值空间分隔的字符串
【发布时间】: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 有什么相关的理由吗?
  • 并非如此。我只是从积累的角度思考
  • 好吧。使用 mapreduce 你可以想出这样的东西,作为起点:jsfiddle.net/briosheje/3r805z6g/3。仅以它为例(尽管它确实接近理想的解决方案),我在休息时想出了这个。

标签: javascript arrays dictionary reduce


【解决方案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);

【讨论】:

  • 附带说明:他需要两个属性(prop1,prop2)。检查更新的问题。
  • @briosheje 感谢您告知更新 :) 也更新了我的答案 :)
【解决方案2】:

你可以使用地图:

["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"

Map 将返回一个包含新项目的新数组。

【讨论】:

  • 我想要一个字符串,并且我有两个属性 prop1 和 prop2 需要按顺序排列
  • 我更新了答案 - 使用 toString 将为您提供最终字符串。你也可以使用.join('')
猜你喜欢
  • 2023-04-01
  • 2019-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多