我有一個數組轉換陣列鍵值對
[
{"field" : "flight1", "value" : "123"},
{"field" : "flight2", "value" : "456"}
]
是有可能成爲關鍵值對?
{
"flight1" : "123",
"flight2" : "456"
}
我有一個數組轉換陣列鍵值對
[
{"field" : "flight1", "value" : "123"},
{"field" : "flight2", "value" : "456"}
]
是有可能成爲關鍵值對?
{
"flight1" : "123",
"flight2" : "456"
}
您可以使用reduce()
並返回對象作爲結果。
var arr = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}]
var result = arr.reduce(function(r, e) {
r[e.field] = e.value;
return r;
}, {});
console.log(result)
您可以映射鍵值對,並將其分配給對象。
var data = [{ field: "flight1", value: "123" }, { field: "flight2", value: "456" }],
result = Object.assign(...data.map(a => ({ [a.field]: a.value })));
console.log(result);
你可以使用一個標準for
循環: -
var data = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}];
var obj = {};
for (var i = 0; i < data.length; i++)
obj[data[i].field] = data[i].value;
console.log(obj);
的new Map()
構造可以爲你做到這一點:
var data = [
{"field": "flight1", "value": "123"},
{"field": "flight2", "value": "456"}
];
var result = new Map(data.map(obj => [obj.field, obj.value]));
這可能會在另一天幫助別人。我試過上面所有的例子,但每次控制檯都給我這樣的東西: { flight1: "123", flight2: "456" }
我的問題是,我正在轉換序列化數組的方式很快,這導致了很多小問題。下面是沒有工作的代碼:
var data = $('#myform').serializeArray();
data = JSON.stringify(data);
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value })));
database.addUser(result);
請注意,flight1和flight2失去了雙引號。下面是我的解決方案:
var data = $('#myform').serializeArray();
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value }))); //result was already turned into a JSON array
database.addUser(result);
NB:這是用於提交用戶信息到使用電子框架
'map'返回對象的數組,而不是一個單一的對象的數據庫(neDB)的碼。 OP希望'{a:1,b:2}',而不是'[{a:1},{b:2}]' – Kobi