我想尽可能不使用jQuery。我在找什么:
var obj = [
{
name: "Sam",
Job: "Developer"
},
{
name: "Mike",
Job: "Brother"
}
];
var testing = obj[name == sam].job // testing equals "Developer"
答案 0 :(得分:2)
您正在寻找Array.filter:
var obj = [
{
name: "Sam",
Job: "Developer"
},
{
name: "Mike",
Job: "Brother"
}
]
var testing = obj
.filter(function(person) {
return person.name == 'Sam'
}).map(function(person) {
return person.Job
})
的console.log(测试)
或者如果您知道自己对第一个感兴趣:
var obj = [
{
name: "Sam",
Job: "Developer"
},
{
name: "Mike",
Job: "Brother"
}
]
var testing = obj
.filter(function(person) {
return person.name == 'Sam'
}) var obj = [
{
name: "Sam",
Job: "Developer"
},
{
name: "Mike",
Job: "Brother"
}
]
var testing = obj
.filter(function(person) {
return person.name == 'Sam'
})
console.log(testing[0] && testing[0].Job)
最后但并非最不重要:如果你知道你只有一场比赛,你可以这样做:
var testing = obj.filter(function(p) { return p.name == 'Sam'; })[0].Job
答案 1 :(得分:2)
所以,你不能像你写的那样简单地做,但是你可以过滤并找到你想要的东西。我已经使它成为一种通用功能,使生活更容易重复使用:
function getArrObjPropertyValue(arr, searchProperty, searchCompare, returnProperty) {
return arr.filter(function(item) {
return item[searchProperty] === searchCompare;
})[0][returnProperty];
}
console.log(getArrObjPropertyValue(obj, 'name', 'Sam', 'Job')); // Developer
答案 2 :(得分:1)
将对象键的比较与分配值分开:
var people = [
{
name: "Sam",
Job: "Developer"
},
{
name: "Mike",
Job: "Brother"
}
];
var testing = null;
for (var person in people) {
if (people[person].name === 'Sam') { testing = people[person].job; }
}