Search code examples
javascriptlodash

Use map to create object and also on a condition


I have an array like this -

details = [{
    id: 1,
    name: 'xyz'
    type: 1
    coun1: 5,
    count2: 6
  },
  {
    id: 2,
    name: 'abc'
    type: 2
    coun1: 4,
    count2: 3
  },
  {
    id: 3,
    name: 'def'
    type: 1
    coun1: 2,
    count2: 8
  }
]

If I do

updatedInfo = details.map(data = > {
  if (type == 1) {
    return {
      totalCount = data.count1 + data.count2
    }
  }
});

I am getting totalCount for type 1, but for others it shouldn't return anything but it is returning undefined.


Solution

  • If you're trying to add another property (total_count) to those objects of type==1, you can filter(), then map() and use the spread {...} syntax to add the new property

    updatedInfo = details.filter(e => e.type === 1)
              .map(e => ({ ...e, total_count: (e.coun1 + e.count2)}))
    

    details = [{
        id: 1,
        name: 'xyz',
        type: 1,
        coun1: 5,
        count2: 6
      },
      {
        id: 2,
        name: 'abc',
        type: 2,
        coun1: 4,
        count2: 3
      },
      {
        id: 3,
        name: 'def',
        type: 1,
        coun1: 2,
        count2: 8
      }
    ]
    
    updatedInfo = details.filter(e => e.type === 1).map(e => ({ ...e,
      total_count: (e.coun1 + e.count2)
    }))
    
    console.log(updatedInfo)