我有一个这样的对象(例如,这就是我们在 chrome 开发工具中看到该对象的方式):
obj: {
1: {...},
2: {...},
3: {...},
4: {...},
5: {...},
}
我有一个像这样的简单数组:
arr: [1,3,5,7]
基本上我希望我的对象与数组中的键保持一致,如下所示:
obj: {
1: {...},
3: {...},
5: {...},
}
目前我的代码是这样的:
var select = (arr, obj) => arr.reduce((r, e) =>
Object.assign(r, obj[e] ? { [e]: obj[e] } : null)
, {});
var output = select(arr, obj);
我不知道为什么,但这有时有效,有时却无效。我不能使用 Jquery。 谁能帮帮我?
最佳答案
你可以使用 Object.fromEntries()
, Object.entries()
, Array.prototype.filter()
和 Array.prototype.includes()
过滤掉不在 arr
中的键:
const obj ={
1: {},
2: {},
3: {},
4: {},
5: {},
};
const arr = [1, 3, 5, 7];
const filtered = Object.fromEntries(
// Note `key` is an `string` here, thus the `+`:
Object.entries(obj).filter(([key]) => arr.includes(+key))
);
console.log(filtered);
或者一个简单的 for
循环,for...of
在这种情况下,再次使用 Array.prototype.includes()
选择你想要的(而不是过滤你不需要的)和Object.prototype.hasOwnProperty()
避免添加 obj
中不存在的键:
const obj ={
1: {},
2: {},
3: {},
4: {},
5: {},
};
const arr = [1, 3, 5, 7];
const filtered = {};
for (const key of arr) {
// Note the `hasOwnProperty` check here to avoid adding the key `7` with a value of `undefined`:
if (obj.hasOwnProperty(key)) filtered[key] = obj[key];
}
console.log(filtered);
或者您可以使用 Array.prototype.reduce()
做同样的事情:
const obj ={
1: {},
2: {},
3: {},
4: {},
5: {},
};
const arr = [1, 3, 5, 7];
const filtered = arr.reduce((newObj, key) => {
// Note we add the values to `newObj` rather than `filtered` now:
if (obj.hasOwnProperty(key)) newObj[key] = obj[key];
// And you always need to return `newObj`:
return newObj;
}, { })
console.log(filtered);
最后,如果您已经在使用 Lodash , 你可以使用 _.pick
:
const obj ={
1: {},
2: {},
3: {},
4: {},
5: {},
};
const arr = [1, 3, 5, 7];
const filtered = _.pick(obj, arr);
console.log(filtered);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.core.min.js"></script>
关于javascript - 如何使用 Javascript 中的数组值过滤对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59591659/