0

I want to create an array of object like this :

array_1 :

array(0, 0, 0, 1, 0, 1, 0, 1, 1);

object_2 :

obj: [
  {
    id: 0,
    fonction: 'hey'
  },
  {
    id: 1,
    fonction: 'hi'
  }
]

So, I want the following output :

result :

obj: [
  {
    id: 0,          // id of object_2
    max: 5,         // number of id value in array_1
    value: 0,       // add an empty value
    fonction: 'hey' // fonction text in oject_2
  },
  {
    id: 1,
    max: 4,
    value: 0,
    fonction: 'hi'
  }
]

Thanks for your help

Janez Kuhar
  • 3,705
  • 4
  • 22
  • 45
Lokomass
  • 41
  • 6

1 Answers1

2

You can just map your existing object, and count the ids inside your array using the filter + length option

const arr = [0, 0, 0, 1, 0, 1, 0, 1, 1];

const target = [
  {
    id: 0,
    fonction: 'hey'
  },
  {
    id: 1,
    fonction: 'hi'
  }
];

console.log( target.map( item => ({
  ...item,
  max: arr.filter( v => item.id === v ).length,
  value: 0
}) ) );
Icepickle
  • 12,689
  • 3
  • 34
  • 48