Lokomass
Lokomass

Reputation: 47

Count occurences of an object field in an array and add it as an additional key

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

Upvotes: 0

Views: 43

Answers (1)

Icepickle
Icepickle

Reputation: 12796

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
}) ) );

Upvotes: 2

Related Questions