簡體   English   中英

如何從鍵值對數組數組中獲取對象數組

[英]How to get an array of objects from an array of key-value pair arrays

我有這樣的數組數組:

var arr = 
[
["Id", "0011900000YDtPXAA1"],
["Name", "account 50"],
["OwnerId", "005190000023IPPAA2"],
["Industry", "Manufacturing"],
["Phone", "312-552-4450"],
["Id", "0011900000YDtPbAAL"],
["Name", "account 54"],
["OwnerId", "005190000023IPPAA2"],
["Industry", "Manufacturing"],
["Phone", "312-552-4454"]
]

我需要每個子數組是一個包含一個鍵-值對的對象。

[
{"Id": "0011900000YDtPXAA1"},
{"Name": "account 50"},
...
]

我試過了

var objArr = new Map(arr);

這將產生我需要的鍵值對,但是將它們全部放在同一個對象中。 如何獲得由一個kv對組成的較小對象的數組?

我會做類似的事情:

1.箭頭功能

 var arr = [ ["Id", "0011900000YDtPXAA1"], ["Name", "account 50"], ["OwnerId", "005190000023IPPAA2"], ["Industry", "Manufacturing"], ["Phone", "312-552-4450"], ["Id", "0011900000YDtPbAAL"], ["Name", "account 54"], ["OwnerId", "005190000023IPPAA2"], ["Industry", "Manufacturing"], ["Phone", "312-552-4454"] ]; const newArr = arr.map(innerArr => ({[innerArr[0]]: innerArr[1]})); console.log(newArr); 

2.沒有箭頭功能

 var arr = [ ["Id", "0011900000YDtPXAA1"], ["Name", "account 50"], ["OwnerId", "005190000023IPPAA2"], ["Industry", "Manufacturing"], ["Phone", "312-552-4450"], ["Id", "0011900000YDtPbAAL"], ["Name", "account 54"], ["OwnerId", "005190000023IPPAA2"], ["Industry", "Manufacturing"], ["Phone", "312-552-4454"] ]; const newArr = arr.map(function (innerArr) { return {[innerArr[0]]: innerArr[1]}; }); console.log(newArr); 

map()方法創建一個新數組,並在調用數組中的每個元素上調用提供的函數。

您可以為此使用傳統的for循環

 var arr = [ ["Id", "0011900000YDtPXAA1"], ["Name", "account 50"], ["OwnerId", "005190000023IPPAA2"], ["Industry", "Manufacturing"], ["Phone", "312-552-4450"], ["Id", "0011900000YDtPbAAL"], ["Name", "account 54"], ["OwnerId", "005190000023IPPAA2"], ["Industry", "Manufacturing"], ["Phone", "312-552-4454"] ]; var arr2 = []; for (var i = 0; i < arr.length; i++) { var sub = {}; sub[arr[i][0]] = arr[i][1]; arr2.push(sub); } console.log(arr2); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM