-2

I have:

arrFrom = [{a: 1, b: 1}, {a: 1, b: undefined}]
arrTo = []

And I try to create new arrTo from arrFrom:

for (let value of arrFrom){
arrTo.push({x: value.a, y: value.b })
}

I need to catch undefined value. I know, I can use function or operators like:

arrTo.push({x: value.a, y: value.b || 0 })
arrTo.push({x: value.a, y: value.b ? value.b: 0 })

Can I use 'in' operator/callback/other style?

EDIT: Thanks for comments, I meant if could use syntax like this(this doesn't work):

arrTo.push({x: value.a, y: ('undefined' in value.b) ? true: 0 }) 
gGotcha
  • 67
  • 5
  • Possible duplicate of [How to check for "undefined" in JavaScript?](https://stackoverflow.com/questions/3390396/how-to-check-for-undefined-in-javascript) – MaxZoom Oct 10 '17 at 15:41
  • 4
    Your dot notation is backwards. It should be `value.a` and `value.b`. – 4castle Oct 10 '17 at 15:42
  • 1
    What's wrong with the solutions you've already proposed? I'm not sure I understand the question. – 4castle Oct 10 '17 at 15:50

2 Answers2

1
arrTo.push({x: a.value, y: b.value || 0 })

I think this is non a OP, 0 will never be applied because always false. Then you can use :

arrTo.push({x: a.value, y: ('value' in b) ? b.value: 0 })

checking undefined is a long story but I always used :

typeof value != 'undefined' && value !== null
David
  • 76
  • 8
  • `a` and `b` aren't defined variables, `value` is, and `a` and `b` are the fields of `value`. – 4castle Oct 10 '17 at 15:53
  • Thanks for idea, unfortunately this doesn't work `arrTo.push({x: a.value, y: ('undefined' in b) ? true: 0 })` – gGotcha Oct 11 '17 at 11:57
  • obj = {a:1 , b:undefined} copy = {}; if( 'b' in obj) copy.b = obj.b; You need to read some Javascript book first... – David Oct 12 '17 at 14:45
0

You meant to do like this:

arrFrom = [{a: 1, b: 1}, {a: 1, b: undefined}];
arrTo = [];
for (var value of arrFrom){
arrTo.push({x: value.a, y: value.b || 0 })
}
console.log(arrTo); // [ { "x": 1, "y": 1 }, { "x": 1, "y": 0 } ]
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231