[英]How to map two arrays of objects, concatenate them, and add an index efficiently
[英]How to use map function for two arrays and concatenate
我有兩個數組。
const test = ["SME","ONE", "TWO"]
const test2 = ["RED"] // can have multiple elements
我正在嘗試映射並返回這樣的對象:
[{SME: "SME", isValid: Y}, {ONE: "ONE", isValid: Y}, {"TWO": isValid: Y}, {"RED": "N"}]
如何使用 map 創建這樣的數據結構?
我試過了 :
test.map((item) => ({
item,
isValid: Y
})
test1.map((item) => ({
item,
isValid: N
})
[...test, ...test2]
這樣它就可以工作,但是還有其他解決方案嗎? 我們不能在開始時組合這兩個數組
您的解決方案還不錯,您也可以使用flatMap :
const test = ["SME", "ONE", "TWO"]; const test2 = ["RED"]; const result = [test, test2].flatMap(arr => { return arr.map(item => { return { item, isValid: arr === test, } }) }) console.log(result)
正如你所建議的:
[...test, ...test2]
或使用concat
test.concat(test2)
或者不創建新數組,直接進入test
Array.prototype.push.apply(test, test2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.