[英]Creating new array of objects from existing arrays, matching on index
我有兩個數組,現在我將它們組合成一個數組,如下所示:
const changeArr = selectedReasons.map((e, i) => e + changeComments[i]);
那行得通,但我最理想的做法是創建一個對象數組,而不是將它們混搭成一個元素,其中每個對象都有一個引用第一個數組的屬性,第二個屬性是來自的相應索引元素第二個數組。
所以想象第一個數組看起來像這樣:
selectedReasons = [
"100A",
"100B"
]
第二個看起來像這樣:
changeComments = [
"Here is my clarifying comment for the first choice.",
"This is a different comment pertaining to my second choice."
]
我想結束的是:
changeArr = [
{
reason: "100A",
comment: "Here is my clarifying comment for the first choice."
},
{
reason: "100B",
comment: "This is a different comment pertaining to my second choice."
}
]
如何調整我當前的代碼,將元素混合到一個對象數組中,每個對象有兩個屬性,這些屬性基於元素的索引匹配?
您可以從 0 循環到原因數組的末尾,並使用原因將新對象推送到新數組,並在索引i
處從它們各自的其他數組中注釋,如下所示:
let changeArr = [];
for (let i = 0; i < selectedReasons.length; i++) {
changeArr.push({ reason: selectedReasons[i], comment: changeComments[i] });
}
這確實意味着如果selectedReasons
數組和changeComments
數組的長度不同,您可能會遇到問題
你只需要返回一個對象
var selectedReasons = [ "100A", "100B" ] var changeComments = [ "Here is my clarifying comment for the first choice.", "This is a different comment pertaining to my second choice." ] var result = selectedReasons.map((reason, i) => ({ reason, change: changeComments[i] })) document.write(`<pre>${JSON.stringify(result, null, 2)}</pre>`)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.