0

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?

2
  • Are you expecting a single Boolean as result if obj.days === 3 && obj.is_enable? Commented May 14, 2017 at 15:15
  • 1
    use some() instead of map(); Commented May 14, 2017 at 15:17

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

9 Comments

=== true is not necessary following && e.is_enable, yes?
I guess it depends on the OP needs, for example jsfiddle.net/Lg0wyt9u/1905
some is es2015? browsers support ?
What if I want to return value instead of just true or false? like jsfiddle.net/s25qx8q5
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.