如何在此对象/数组中搜索第一个元素来获取字段名称?
在此示例中,如果我正在搜索 #999999
,我需要获得第二个
colors = {
first: ['#cccccc', '#999999'],
second: ['#999999', '#626262'],
third: ['#eeeeee', '#afafaf']
};
我尝试过这样的事情:
for(var field in colors) {
if(colors.hasOwnProperty(field)) {
if(colors[field] === '#999999') {
console.log(field); // gives 'second'
var color1 = colors[field][0],
color2 = colors[field][1];
}
}
}
也许这可以变得更加简单。
最佳答案
尝试使用 Object.keys()
、 Array.prototype.filter()
;返回对象的属性名称,其中 "#999999"
位于数组的索引 0
var colors = {
first: ['#cccccc', '#999999'],
second: ['#999999', '#626262'],
third: ['#eeeeee', '#afafaf']
};
var n = "#999999";
var res = Object.keys(colors).filter(function(key, index) {
return colors[key][0] === n
});
console.log(res[0])
关于javascript - 在对象中搜索数组的第一个元素以获取字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33717553/