我有下面的对象,(总是)有2个属性。它将始终有两个属性。3个属性是不可能的:
var people = {
'John': { ... },
'Peter': { ... }
}
我有一个变量var name = 'John'
。
当'Peter'
的值为'John'
时,有没有简单的方法来获取属性name
的值?而不是硬编码成John en Peter的名字。因此,该函数必须获得与变量name
中的值相反的属性
发布于 2020-10-03 05:53:26
Object.keys
将为您提供一个属性名称数组。
filter
允许您过滤该数组。
所以:
const name = "John";
const people = {
'John': 1,
'Peter': 1
};
const [result] = Object.keys(people).filter(person => person !== name);
console.log({
result
});
发布于 2020-10-03 05:52:33
let name = 'John'; // or whatever
let names = Object.keys(people);
let otherName = names.find(n => n !== name);
people[otherName] // this gives you the value of the other name's property
发布于 2020-10-03 05:54:53
我写了一个简单的函数,可以做到这一点。它需要一个键和一个对象。它通过给定键的逆键返回给定对象中元素的值。仅当对象只有两个关键点时才有效。
var people = {
'John': { 'b':[3,4] },
'Peter': { 'a':[1,2] }
}
getInverseObjectElem = (key,object) => { // Define function 'getInverseObjectElem'
listOfObjectKeys = Object.keys(object) // Create an array of the object keys
inverseKey = listOfObjectKeys.filter(k => k != key)[0] // filter the list of keys, and get the first key that doesnt match the given key.
return object[inverseKey] // Return the value in the object, by the inverseKey
}
console.log(getInverseObjectElem('John',people))
https://stackoverflow.com/questions/64178592
复制相似问题