简体   繁体   English

如何对两个数组使用map函数并连接

[英]How to use map function for two arrays and concatenate

I have two arrays.我有两个数组。

const test = ["SME","ONE", "TWO"]
const test2 = ["RED"]  // can have multiple elements

I am trying to map over this and return an object like this :我正在尝试映射并返回这样的对象:

[{SME: "SME", isValid: Y}, {ONE: "ONE", isValid: Y}, {"TWO": isValid: Y}, {"RED": "N"}]

How can I create such Data structure using map ?如何使用 map 创建这样的数据结构?

I tried :我试过了 :

test.map((item) => ({
   item,
    isValid: Y
})

test1.map((item) => ({
   item,
isValid: N
})

[...test, ...test2]

This way it works , but any other solution for this ?这样它就可以工作,但是还有其他解决方案吗? We can not combine these two arrays at start我们不能在开始时组合这两个数组

Your solution is not bad, you could also use flatMap :您的解决方案还不错,您也可以使用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)

As you suggestet:正如你所建议的:

[...test, ...test2]

Or using concat或使用concat

test.concat(test2)

Or without creating a new array, just pushing into test或者不创建新数组,直接进入test

Array.prototype.push.apply(test, test2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM