在对象数组中查找颜色属性

时间:2018-05-03 10:44:40

标签: javascript

尝试在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))

3 个答案:

答案 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;
	}
}