英文:
JS console log value in array of object attributes
问题
在Python中,这很简单,可以使用以下方式将特定值与对象数组的特定属性进行比较并记录到控制台:
print(val in [x['attribute'] for x in objects])
在JavaScript中,你可以使用以下方式执行包含操作并记录到控制台:
console.log(objects.map(x => x.attribute).includes(val).toString());
从你的描述中看,你似乎已经尝试了这种方法,但它似乎没有按预期工作。你是否需要进一步检查输入数据和变量的值,以确保它们是正确的?如果你仍然遇到问题,可能需要在你的代码中添加一些调试输出,以便更好地理解发生了什么。
英文:
I'm trying to log to console whether an array of objects contains a specific value on a specific attribute of one of these such objects.
in Python this is as simple as
print(val in [x['attribute'] for x in objects])
In JS, I think the inclusion operation should function as
objects.map(x=>x.attribute).includes(val);
// console.log(objects.map(x=>x.attribute).includes(val).toString());
From reading, I've come to understand that raw booleans cannot be logged so they must be converted to string first.
the above is neither logging "true" or "false". So am I doing something wrong?
答案1
得分: 0
你的代码是正确的,如果你想要记录一个对象数组是否包含一个特定属性的特定值。
确定对象是否包含一个值会返回一个布尔值。
你是否试图记录具有包含特定值的属性的对象?如果是这样,我会使用filter
而不是map
,像这样:
objects.filter(x => x. attribute.includes(val))
。
英文:
Your code is correct if you want to log whether an array of objects contains a specific value on a specific attribute of one of these such objects.
Whether the object contains a value returns a boolean.
Are you trying to log the objects that have an attribute that contain a specific value? If so, I would use filter in stead of map, like this:
objects.filter(x => x. attribute.includes(val))
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论