将 Javascript 对象数组缩减为字符串

我想将项目映射到数量,就像这样item: quantity。


假设我有一个对象数组:


{

  Item: "",

  Quantity : 2,

},

{

  Item: "B",

  Quantity : 7,

},

{

  Item: "",

  Quantity : "",

}

]

我应该得到以下字符串输出


`: 2, B: 7`

我已经尝试了基本的 for 循环和 if 条件,如下所示,但我想要更短的


var str = "";

for (var a = 0; a < array.length; a++) {

  str += array[a].Item + ",";

  str += array[a].Quantity;

  if (a != array.length - 1) {

    str += ",";

  }

}


海绵宝宝撒
浏览 82回答 2
2回答

开满天机

使用 array.reduce() 将是一种更好、更清洁的方法。let arr = [{ Item: "", Quantity: 2 }, { Item: "B", Quantity: 7 }, { Item: "", Quantity: "" }]const groupBy = arr.reduce(function (total, obj)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;total += (obj.Item + ":" + (obj.Quantity + " , "));&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return total;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, 0);&nbsp;

斯蒂芬大帝

您可以映射这些值并加入它们。var array = [{ Item: "", Quantity: 2 }, { Item: "B", Quantity: 7 }, { Item: "", Quantity: "" }],&nbsp; &nbsp; string = array&nbsp; &nbsp; &nbsp; &nbsp; .filter(({ Item, Quantity }) => Item || Quantity)&nbsp; &nbsp; &nbsp; &nbsp; .map(({ Item, Quantity }) => `${[Item ? Item : "", Quantity ? Quantity: ""].join(': ')}`)&nbsp; &nbsp; &nbsp; &nbsp; .join(', ');&nbsp; &nbsp;&nbsp;console.log(string);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript