[英]Convert array of strings to objects and assign specific key
我正在嘗試轉換以下字符串數組:
["one", "two", "three"]
轉換為具有特定鍵(例如,數字)的JSON對象數組,如下所示:
[
{
number: 'one'
},
{
number: 'two'
},
{
number: 'three'
}
]
只需使用Array.prototype.map()遍歷array
中的所有元素並創建一個新元素,同時將它們轉換為具有所需結構的object
。
您可以使用ES6減少代碼行,但我還提供了ES5版本:
// ES6: const arrayOfObjectsES6 = ["one", "two", "three"].map(number => ({ number })); console.log(arrayOfObjectsES6); // ES5: var listOfObjectsES5 = ["one", "two", "three"].map(function(value) { return { number: value }; }); console.log(listOfObjectsES5);
然后,您可以只使用JSON.stringify()
來獲取其JSON string
表示形式:
JSON.stringify(arrayOfObjectsES6);
如果您希望能夠使用"number"
以外的鍵來重用此功能:
function getArrayOfObjectsES6(values, key) { return values.map(value => ({ [key]: value })) } console.log( JSON.stringify(getArrayOfObjectsES6(["one", "two", "three"], 'ES6')) ); function getArrayOfObjectsES5(values, key) { return values.map(function(value) { var obj = {}; obj[key] = value; return obj; }); } console.log( JSON.stringify(getArrayOfObjectsES6(["one", "two", "three"], 'ES5')) );
請注意,您也可以將常規for
,但我認為map()
是此處更簡潔,最簡潔的選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.