0

I have an array of object

const data = [{id:"1", "name":"ab", value:100, doubleval:'344'},{id:"2", "name":"ab", value:200,doubleval:'122'},{id:"1", "name":"bc", value:100, doubleval:'123'},{id:"1", "name":"bc", value:300, doubleval:'44'}]

so I want to get value from this So I tried using lodash

return _.filter(data, (item) => {
            return (item === 'ab') ? item?.value : budgetRangePlan?.doubleval
      })

This returns an array of object,

here I was expecting value as 100 and 200 respectively.

How do I fix this ?

2
  • 1
    Use _.map() or instead of _.filter(). Commented Apr 22, 2021 at 5:23
  • map returns an array of object as well.. I wanted to get the exact value Commented Apr 22, 2021 at 5:24

2 Answers 2

1

Filter is for collect element fits a boolean condition. For your code I think that you could try

let rs = data.map((data) => (data.name == 'ab' ? data.value : data.doubleval))
Sign up to request clarification or add additional context in comments.

Comments

0

This should help you:

const data = [{id:"1", "name":"ab", value:100, doubleval:'344'},{id:"2", "name":"ab", value:200,doubleval:'122'},{id:"1", "name":"bc", value:100, doubleval:'123'},{id:"1", "name":"bc", value:300, doubleval:'44'}]

let result = data.map(a => a.name == 'ab' ? a.value : a.doubleval);

console.log(result)

References

3 Comments

Actually I want to return a single value for this
I edited the answer. Does it fix your problem now?
Forget that edit, it won't return a single value. I'm a bit confused...:D You want to return either the value 100 or 200 if name is 'ab'?

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.