假设我有一个对象数组 [] 和一个数字数组。
let objects = [
{name: apple, id:1},
{name: banana, id:2},
{name: orange, id:5}
];
let numbers = [5, 1];
我想过滤对象数组,所以只保留与数字匹配的id,并更改顺序以匹配数字数组。
result should be [{name: orange, id:5} , {name: apple, id:1} ]
我可以用 javascript 对象原型(prototype)来做吗?或者我可以使用像 lodash 这样的第三方工具吗?
我试过下面的代码,但它保持了原始列表的顺序:
result = object.filter(p => {
return numbers.includes(parseInt(p.id));
});
最佳答案
您可以通过查找对象来映射想要的项目。
var objects = [{ name: 'apple', id: 1 }, { name: 'banana', id: 2 }, { name: 'orange', id: 5 }],
numbers = [5, 1],
result = numbers.map(id => objects.find(o => o.id === id));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
查找和重新排序的规范解决方案可能是使用哈希表或 Map
快速访问 O(1) 并映射所需的部分。
例如,这里有一个通过传递原始数据数组、所需值数组和 key 来抽象 key 的解决方案。
const
getObjects = (data, values, key) => values.map(
Map.prototype.get,
objects.reduce((m, o) => m.set(o[key], o), new Map)
),
objects = [{ name: 'apple', id: 1 }, { name: 'banana', id: 2 }, { name: 'orange', id: 5 }],
values = ['banana', 'apple', 'orange'],
result = getObjects(objects, values, 'name');
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何过滤对象数组但更改顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53648296/