我需要用对象填充id数组。换句话说,我有。 ID数组:
var orderArray = ["5ace454a2b22e17597d0e694", "5acde7c0f7d2520e3b205971", "5ad2086bf05ad342dc723ea1"]
对象数组:
var objectsArray = [ { _id: 5acde7c0f7d2520e3b205971,
name: 'Dinner',
restaurant: 5a68d8ea17d9e4308e6400c3,
created: 2018-04-11T10:47:28.957Z,
status: true,
products: [ [Object] ] },
{ _id: 5ace454a2b22e17597d0e694,
name: 'Test',
restaurant: 5a68d8ea17d9e4308e6400c3,
image:
{ _id: 5ad23ed177bcd07303f62899,
filename: 'rJKCR2k2f-1523728081111.jpeg',
destination: 'images',
binded: true },
created: 2018-04-11T17:26:34.186Z,
status: false,
products: [ [Object], [Object] ] },
{ _id: 5ad2086bf05ad342dc723ea1,
name: 'Test',
restaurant: 5a68d8ea17d9e4308e6400c3,
image: null,
created: 2018-04-14T13:55:55.449Z,
status: true,
products: [] } ]
您可以根据ID对对象数组进行排序...或者将ID数组映射到对象数组。可能我更喜欢第二种选择。 但我的方法不起作用
orderArray.map(id => objectsArray.filter(obj => obj._id == id))
结果应为:objectsArray按orderArray中的元素顺序排序
解决方案:几天前我已经打开过这个问题了:Merging 2 arrays with different value types
我有同样的问题。 orderArray是对象数组(不是字符串),因此为了使它工作,我需要应用我之前找到的解决方案(Array.filter和Array.find函数都运行良好): 但按照我的方式,它只会在以下情况下起作用:
order_array.map(String).map(e => objectsArray.find(a => a._id == e))
//as well as
order_array.map(String).map(e => objectsArray.filter(a => a._id == e))
答案 0 :(得分:4)
map
第一个数组用第二个对应的元素填充它:
var orderArray = ["5ace454a2b22e17597d0e694", "5acde7c0f7d2520e3b205971", "5ad2086bf05ad342dc723ea1"]
var objectsArray = [ { _id: '5acde7c0f7d2520e3b205971',
name: 'Dinner',
restaurant: '5a68d8ea17d9e4308e6400c3',
created: '2018-04-11T10:47:28.957Z',
status: true,
products: [ [Object] ] },
{ _id: '5ace454a2b22e17597d0e694',
name: 'Test',
restaurant: '5a68d8ea17d9e4308e6400c3',
image:
{ _id: '5ad23ed177bcd07303f62899',
filename: 'rJKCR2k2f-1523728081111.jpeg',
destination: 'images',
binded: true },
created: '2018-04-11T17:26:34.186Z',
status: false,
products: [ [Object], [Object] ] },
{ _id: '5ad2086bf05ad342dc723ea1',
name: 'Test',
restaurant: '5a68d8ea17d9e4308e6400c3',
image: null,
created: '2018-04-14T13:55:55.449Z',
status: true,
products: [] } ]
var sorted = orderArray.map((e) => { return objectsArray.find((a) => { return a._id == e})})
console.log(sorted)

答案 1 :(得分:1)
你应该能够:
objectsArray.filter(obj => ordersArray.includes(obj._id));
如果我理解正确的话。
答案 2 :(得分:0)
使用map
/ find
(而不是filter
):
let mappedArray = orderArray.map(id => objectsArray.find(obj => obj._id == id));
map
s orderArray
对象数组,其中find
来自objectsArray
的对象与当前_id
具有相同的id
{1}}。
注意:如果objectsArray
中没有与id
匹配的对象,则会返回null
。