I have an array like this:
var Items = new Array({ name: "aaa", field: "bbb", val: true },
{ name: "ccc", field: "ddd", val: false })
I want to check if a certain object has same field's value as defined in the field
& val
of the array.
I did this:
var obj = {bbb: false, ddd: false} #(I'm getting the obj from API, but this is what I have when I print obj to log)
_.each(Items, function(item){
if (obj[item.field] === item.val)
console.log(obj[item.field],"=",item.val);
});
But I got undefind=undefined
.
When I tried obj['bbb']
OR obj[String(item.field)]
, I got the value.
Also, see following logs inside the loop:
console.log(typeof item.field, typeof "bbb");
=> string string
console.log(obj["bbb"], obj[item.field], obj[String(item.field)], item.field);
=> false undefined false "bbb"
Does Anybody know why this happens?
To compare objects, it's simpler to just use _.isEqual
(see http://underscorejs.org/#isEqual ). Javascript has some very wierd quirks, for example http://www.sitepoint.com/javascript-truthy-falsy/
An objects property name must be a string , any string is valid including an empty string (the truth is the same is really true of arrays, except that the numbers get converted to a string (for example Items[0]
is really Items["0"]
)).
When you are comparing to obj[item.val]
you are (for the sample array you provided) checking for a property name that is a boolean
which isn't valid. When you instead use obj[String(item.val)]
you are first converting the value true
or false
to a string so it becomes "true"
or "false"
.
Here's a link to a jsfiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.