如何同时索引 javascript 对象的多个属性
How to index multiple properties on javascript object at the same time
假设我有一个 JavaScript 对象,例如:
var x = {
'one': 1,
'two': 2,
'three': 3
}
然后我有一个数组,其中包含我想从此对象访问的键。
这是我的钥匙:
var keys = ['one', 'two'];
现在当我使用这些键从对象中拉出我想要的东西时,它应该是这样的...
{
'one': 1,
'two': 2
}
我的伪代码思维将代码想象成这样:
var x = {
'one': 1,
'two': 2,
'three': 3
}
var keys = ['one', 'two'];
var answer = x[keys];
但我知道这实际上行不通...
在 javascript 中是否有一种优雅的方式来做到这一点?使用数组索引对象的多个属性?
我可以想象一个使用暴力破解的 for-loop
版本,但我想知道这是否是我不知道的 JavaScript 功能?
想法?
这需要一些代码,但我认为最接近的方法是使用 Object.fromEntries
将键映射到新对象。
var x = {
'one': 1,
'two': 2,
'three': 3
};
var keys = ['one', 'two'];
const newObj = Object.fromEntries(
keys.map(key => [key, x[key]])
);
console.log(newObj);
我想这就是你想要的;
var x = {
'one': 1,
'two': 2,
'three': 3
}
var keys = ['one', 'two'];
let res = {};
keys.forEach(key => {res[key] = x[key]})
console.log(res)
您可以使用 Array#reduce
来获得最高性能 O(n)
时间复杂度,就像这样。
var x = { 'one': 1, 'two': 2, 'three': 3};
var keys = ['one', 'two', 'five'];
const result = keys.reduce((acc, curr) => (curr in x && (acc[curr] = x[curr]), acc), {});
console.log(result);
假设我有一个 JavaScript 对象,例如:
var x = {
'one': 1,
'two': 2,
'three': 3
}
然后我有一个数组,其中包含我想从此对象访问的键。
这是我的钥匙:
var keys = ['one', 'two'];
现在当我使用这些键从对象中拉出我想要的东西时,它应该是这样的...
{
'one': 1,
'two': 2
}
我的伪代码思维将代码想象成这样:
var x = {
'one': 1,
'two': 2,
'three': 3
}
var keys = ['one', 'two'];
var answer = x[keys];
但我知道这实际上行不通...
在 javascript 中是否有一种优雅的方式来做到这一点?使用数组索引对象的多个属性?
我可以想象一个使用暴力破解的 for-loop
版本,但我想知道这是否是我不知道的 JavaScript 功能?
想法?
这需要一些代码,但我认为最接近的方法是使用 Object.fromEntries
将键映射到新对象。
var x = {
'one': 1,
'two': 2,
'three': 3
};
var keys = ['one', 'two'];
const newObj = Object.fromEntries(
keys.map(key => [key, x[key]])
);
console.log(newObj);
我想这就是你想要的;
var x = {
'one': 1,
'two': 2,
'three': 3
}
var keys = ['one', 'two'];
let res = {};
keys.forEach(key => {res[key] = x[key]})
console.log(res)
您可以使用 Array#reduce
来获得最高性能 O(n)
时间复杂度,就像这样。
var x = { 'one': 1, 'two': 2, 'three': 3};
var keys = ['one', 'two', 'five'];
const result = keys.reduce((acc, curr) => (curr in x && (acc[curr] = x[curr]), acc), {});
console.log(result);