0

I need help to create an array of objects from two exiting array

["A","B","C"]
[1,2,3] 

What I want is something like the below:

[{name: "A", id: 1, trash: false},{name: "B", id: 2, trash: false},{name: "C", id: 3, trash: false}]

properties should be defined as I want it like name and id and the value of them should come from existing arrays.

MaHo
  • 63
  • 1
  • 8

2 Answers2

2

Hope this code helping you

const array = ["A","B","C"]
const num = [1,2,3] 
array.map((o,index)=>({name: o,id:num[index],trash:false}))
Viktor M
  • 301
  • 1
  • 7
1

You can try using Array.prototype.map() that creates a new array populated with the results of calling a provided function on every element in the calling array.

var arr1 = ["A","B","C"]
var arr2 = [1,2,3] 
var resArr = arr1.map((i,idx) => ({name: i, id: arr2[idx], trash: false}));
console.log(resArr);
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • it is a very nice solution thank you very much but I forgot to mention in arr2 numbers are saved as string so is there any quick way to convert them to the intiger in the map() method? – MaHo Sep 23 '21 at 13:19
  • @MohammadKhavari, simply prefix the arr2 value with `+`....like `id: +arr2[idx]`:) – Mamun Sep 23 '21 at 13:24