假设我有一个对象数组:
array=[
{
"Item": "A"
"Quantity" : 2
},
{
"Item": "B"
"Quantity" : 7
},
{
"Item": "C"
"Quantity" : 1
}
]
我想知道如何获得以下字符串输出:
(A, 2), (B, 7), (C,1)
这不是最优雅的方式,但它很容易理解:
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);
您可以映射值并加入它们。
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);
您可以使用
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);
你可以像这样map
Object.values
和join
:
map
循环遍历数组Object.values(a)
返回一个这样的数组:["A", 2]
join
他们使用和使用()
包裹template literalsmap
从join
加入生成的字符串数组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)