我有一个对象,可能看起来像这样:
var nicknames = []
nicknames.push({id:"100", name:"john", id2:"200", name2:"max"});
但对象也可能是这样的:
nicknames.push({id:"200", name:"max", id2:"100", name2:"john"});
键和值可能会被交换。
如果提供"max"的名称或"200"的ID,我如何获取名称和ID"john"和"100"?
我有一个对象,可能看起来像这样:
var nicknames = []
nicknames.push({id:"100", name:"john", id2:"200", name2:"max"});
nicknames.push({id:"200", name:"max", id2:"100", name2:"john"});
键和值可能会被交换。
如果提供"max"的名称或"200"的ID,我如何获取名称和ID"john"和"100"?
var found_name, found_id;
for(var i = 0; i < nicknames.length; i++) {
var nn = nicknames[i];
if (nn.name == "max" || nn.id = "200") {
found_name = nn.name2;
found_id = nn.id2;
break;
} else if (nn.name2 == "max" || nn.id2 = "200") {
found_name = nn.name;
found_id = nn.id;
break;
}
}
var nicknames= [ {id:"100", nickname:"John"}, {id:"200", nickname:"Michael"} ];
function getByName(arr, value) {
for (var i=0, iLen=arr.length; i<iLen; i++) {
if (arr[i].nickname == value) return arr[i];
}
}
var object = getByName(nicknames, "John");
// Will show '100'
alert(object.id);
您可以在这里看到实际效果:http://jsfiddle.net/b1yL28at/
var nicknames = []
nicknames.push({
id: "100",
name: "john",
id2: "200",
name2: "max"
});
var idIndex = {},
nameIndex = {};
nicknames.forEach(function(currentNickName) {
idIndex[currentNickName.id] = {
id: currentNickName.id2,
name: currentNickName.name2
};
idIndex[currentNickName.id2] = {
id: currentNickName.id,
name: currentNickName.name
};
nameIndex[currentNickName.name] = {
id: currentNickName.id2,
name: currentNickName.name2
};
nameIndex[currentNickName.name2] = {
id: currentNickName.id,
name: currentNickName.name
};
});
然后看起来像这样
console.log(nameIndex, idIndex);
{ john: { id: '200', name: 'max' }, max: { id: '100', name: 'john' } }
{ '100': { id: '200', name: 'max' }, '200': { id: '100', name: 'john' } }
console.log(nameIndex["max"]);
// { id: '100', name: 'john' }
console.log(nameIndex["john"]);
// { id: '200', name: 'max' }
console.log(idIndex["100"]);
// { id: '200', name: 'max' }
console.log(idIndex["200"]);
// { id: '100', name: 'john' }
var nicknames = [{id:"100", name:"john", id2:"200", name2:"max"},
{id:"300", name:"tim", id2:"400", name2:"fred"}];
function getOther(nameOrId) {
var nickname;
for (var i=0, iLen=nicknames.length; i<iLen; i++) {
nickname = nicknames[i];
if (nickname.id == nameOrId || nickname.name == nameOrId) {
return [nickname.id2, nickname.name2];
}
if (nickname.id2 == nameOrId || nickname.name2 == nameOrId) {
return [nickname.id, nickname.name];
}
}
}
console.log(getOther('max')); // ["100", "john"]
console.log(getOther('100')); // ["200", "max"]
console.log(getOther('400')); // ["300", "tim"]
function getOther(nameOrId) {
var result;
nicknames.some(function (nickname) {
if (nickname.id == nameOrId || nickname.name == nameOrId) {
return result = [nickname.id2, nickname.name2];
}
if (nickname.id2 == nameOrId || nickname.name2 == nameOrId) {
return result = [nickname.id, nickname.name];
}
});
return result;
}
但我看不出有什么意义,代码行数完全相同,也没有更加清晰易懂(当然这只是我的个人观点)。