Alan Jenshen
Alan Jenshen

Reputation: 3239

return non array in using map

I used map to loop but it returned an array, not sure I should use something else like forEach. I have this initial object.

data.discounts: [{
    days: 3,
    is_enable: true
},{
    days: 10,
    is_enable: false
}]

Then I do the checking on is_enable

const newObj = {
    "disableDiscount_3": !isEmpty(data.discounts) ? (data.discounts.map(obj => obj.days === 3 && obj.is_enable === true ? true : false)) : ''
}

then it became

newObj.disableDiscount_3 = [{
    true,
    false,
    false,
    false
}]

What I want is actually just true or false like: newObj.disableDiscount_3 = true What should I do?

Upvotes: 0

Views: 348

Answers (1)

Nenad Vracar
Nenad Vracar

Reputation: 122027

map() method is not meant to be used for that, instead you can use some() that will check if specified object exists and return true/false.

var discounts = [{
  days: 3,
  is_enable: true
}, {
  days: 10,
  is_enable: false
}]

var check = discounts.some(e => e.days == 3 && e.is_enable === true);
console.log(check)

To first find specific object you can use find() method and if the object is found then you can take some property.

var data = {
  discounts: [{
    days: 3,
    is_enable: true,
    value: 123
  }, {
    days: 10,
    is_enable: false
  }]
}

var obj = {
  "discount_3": (function() {
    var check = data.discounts.find(e => e.days == 3 && e.is_enable === true)
    return check ? check.value : ''
  })()
}

console.log(obj)

Upvotes: 2

Related Questions