Home > database >  How to use map function for two arrays and concatenate
How to use map function for two arrays and concatenate

Time:07-05

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 ?

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

CodePudding user response:

Your solution is not bad, you could also use 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)

CodePudding user response:

As you suggestet:

[...test, ...test2]

Or using concat

test.concat(test2)

Or without creating a new array, just pushing into test

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