尝试在property
array
中找到匹配的objects
。我无法让find
选出colour
。有任何想法吗?我无法得到console.log
const tag = 'lecture';
const eventColour = [
{
type: "lecture",
colour: "red"
},
{
type: "social",
colour: "blue"
},
{
type: "break",
colour: "green"
}
]
eventColour.filter(obj => Object.keys(obj).find(e => obj[e].type == tag))
答案 0 :(得分:0)
如果您的目标是使用匹配的colour
获取对象的type
,那么find
将与属性访问者结合使用:
const obj = eventColour.find(obj => obj.type === tag);
const colour = obj && obj.colour;
如果没有匹配,我们需要&&
后卫。
直播示例:
const tag = 'lecture';
const eventColour = [
{
type: "lecture",
colour: "red"
},
{
type: "social",
colour: "blue"
},
{
type: "break",
colour: "green"
}
];
const obj = eventColour.find(obj => obj.type === tag);
const colour = obj && obj.colour;
console.log(tag + " => " + colour);
// Example of not finding it:
const tag2 = "not found";
const obj2 = eventColour.find(obj => obj.type === tag2);
const colour2 = obj2 && obj2.colour;
console.log(tag2 + " => " + colour2);

答案 1 :(得分:0)
试试这个
const tag = 'lecture';
const eventColour = [{
type: "lecture",
colour: "red"
},
{
type: "social",
colour: "blue"
},
{
type: "break",
colour: "green"
}
]
eventColour.forEach(function(obj) {
if (obj['type'] == tag) {
console.log(obj['colour'])
}
});
答案 2 :(得分:0)
使用旧的循环有什么问题?
const tag = 'social';
const eventColour = [
{
type: "lecture",
colour: "red"
},
{
type: "social",
colour: "blue"
},
{
type: "break",
colour: "green"
}
]
for(var i = 0; i < eventColour.length;i++)
{
var obj = eventColour[i];
if (obj['type'] == tag)
{
console.log(obj['colour']);
break;
}
}