我有一个相当简单的JavaScript对象,我需要使用其他已知属性来引用其中一个属性。
{
"PM":"Joe Smith",
"Consultant":"joesmith@joesmith.com",
"Project":"ContainerStore",
"Notes":"This is my awesome note"
}
所以以上面的例子为例,我将有项目,顾问& PM和我需要返回给定组合的注释。
答案 0 :(得分:2)
您认为可以使用ES6 ARRAY.FIND 这是浏览器对它的支持:
Chrome:45.0
Firefox(Gecko):25.0(25.0)
Internet Explorer:不支持
边缘:12
歌剧:32.0
Safari:7.1
所以,让我们知道PM,顾问和项目,可能是这样的对象:
var known = {
"PM": "John Smith",
"Consultant": "Jim Bob",
"Project": "Awesome Project"
}
然后我们在数组中有一个对象列表,如下所示:
var listOfProjects = [ {....}...]
我们想要告诉我们的工作是Find the object that matches my known object
。幸运的是,JavaScript数组有find
方法,我们可以在函数中传递,如下所示:
var foundProject = listOfProjects.find(function(project){
return project["PM"] === known["PM"] &&
project["Consultant"] === known["Consultant"] &&
project["Project"] === known["Project"]
})
或者我们可以使用另一个名为every
的高阶函数使其更清晰一些:
// Loop through the listOfProjects and return the first one that
// returns true
var foundProject = listOfProjects.find(function(project){
// Loop through all of the keys inside of our known object
// and return true or false if every single one matches
// the given condidtion
return Object.keys(known).every(function(knownKey){
// use the key to see if known at knownKey is equal to
// what you find inside of project at the same key
return known[knownKey] === project[knownKey]
})
})
无论哪种方式,foundProject都是实际的项目对象,所以如果我们只想要“Notes”键,我们就可以这样做:
var notesForFoundProject = foundProject["Notes"]
如果你不能使用Array.find,下面的代码将是相同的:
var known = {...}
var listOfProjects = [...]
var found;
for(var i = 0; i < listOfProjects.length; i++){
var current = listOfProjects[i]
if(current["PM"] === known["PM"] &&
current["Consultant"] === known["Consultant"] &&
current["Project"] === known["Project"]){
found = current;
break;
}
}
var notes = found["Notes"] || false