Javascript对象数组到字符串

问题描述 投票:0回答:4

假设我有一个对象数组:

array=[
  {
    "Item": "A"
    "Quantity" : 2
  },
  {
    "Item": "B"
    "Quantity" : 7
  },
  {
    "Item": "C"
    "Quantity" : 1
  }
]

我想知道如何获得以下字符串输出:

(A, 2), (B, 7), (C,1)
javascript arrays string
4个回答
3
投票

这不是最优雅的方式,但它很容易理解:

array = [{
    "Item": "A",
    "Quantity": 2
  },
  {
    "Item": "B",
    "Quantity": 7
  },
  {
    "Item": "C",
    "Quantity": 1
  }
];

var str = "";
for (var a = 0; a < array.length; a++) {
  str += "(";
  str += array[a].Item + ",";
  str += array[a].Quantity + ")";
  if (a != array.length - 1) {
    str += ",";
  }
}
console.log(str);

1
投票

您可以映射值并加入它们。

var array = [{ Item: "A", Quantity: 2 }, { Item: "B", Quantity: 7 }, { Item: "C", Quantity: 1 }],
    string = array
        .map(({ Item, Quantity }) => `(${[Item, Quantity].join(', ')})`)
        .join(', ');
    
console.log(string);

0
投票

您可以使用

array.map(function(item){ return "(" + item.Item + "," + item.Quantity + ")"}).join(",");

var array=[
  {
    "Item": "A",
    "Quantity" : 2
  },
  {
    "Item": "B",
    "Quantity" : 7
  },
  {
    "Item": "C",
    "Quantity" : 1
  }
];
var result = array.map(function(item){ return "(" + item.Item + "," + item.Quantity + ")"}).join(",");
console.log(result);

0
投票

你可以像这样map Object.valuesjoin

  • 使用map循环遍历数组
  • Object.values(a)返回一个这样的数组:["A", 2]
  • join他们使用和使用()包裹template literals
  • 使用另一个mapjoin加入生成的字符串数组

const array = [
  {
    "Item": "A",
    "Quantity" : 2
  },
  {
    "Item": "B",
    "Quantity" : 7
  },
  {
    "Item": "C",
    "Quantity" : 1
  }
]

const str = array.map(a => `(${ Object.values(a).join(", ") })`)
                 .join(", ")
                 
console.log(str)

如果你对(A,2), (B,7), (C,1)没有任何空间,你可以简单地使用

const array=[{"Item":"A","Quantity":2},{"Item":"B","Quantity":7},{"Item":"C","Quantity":1}]

const str = array.map(a => `(${ Object.values(a) })`).join(", ")
console.log(str)
© www.soinside.com 2019 - 2024. All rights reserved.