我有两个对象数组。一个具有一个具有ID列表的id属性,第二个具有一个具有唯一id属性的对象。我想用第一个列表过滤第二个数组中的id并获取数据。
const data1 = [{
name: 'A',
ids: [1, 2, 3]
}, {
name: 'B',
ids: [4, 5, 6]
}, {
name: 'C',
ids: [7, 8, 9]
}]
const data2 = [{
id: 1,
color: 'red'
}, {
id: 2,
color: 'black'
}, {
id: 3,
color: 'blue'
}, {
id: 4,
color: 'yellow'
}, {
id: 5,
color: 'green'
}, {
id: 6,
color: 'pink'
},
{
id: 7,
color: 'orange'
}, {
id: 8,
color: 'white'
}, {
id: 9,
color: 'teal'
}
]
const arrayToObject = (array) =>
array.reduce((obj, item) => {
obj[item.id] = item
return obj
}, {})
console.log(arrayToObject(data2))
const newData = data1.map(item => {
return {
name: item.name,
data: item.ids.map(i => arrayToObject(data2)[i])
}
})
console.log(newData)
预期输出:
[
{
"name": "A",
"data": [
{
"id": 1,
"color": "red"
},
{
"id": 2,
"color": "black"
},
{
"id": 3,
"color": "blue"
}
]
},
{
"name": "B",
"data": [
{
"id": 4,
"color": "yellow"
},
{
"id": 5,
"color": "green"
},
{
"id": 6,
"color": "pink"
}
]
},
{
"name": "C",
"data": [
{
"id": 7,
"color": "orange"
},
{
"id": 8,
"color": "white"
},
{
"id": 9,
"color": "teal"
}
]
}
]
我确实做到了这一点,但是我想可能会有一个更好的干净,高性能的解决方案。请给我建议。
P.S:我也愿意使用lodash。
答案 0 :(得分:1)
您已经熟悉标准方法:
id
创建字典或地图data1
迭代Array.map()
ids
并从字典中取出项目您可以使用lodash缩短代码:
const data1 = [{"name":"A","ids":[1,2,3]},{"name":"B","ids":[4,5,6]},{"name":"C","ids":[7,8,9]}]
const data2 = [{"id":1,"color":"red"},{"id":2,"color":"black"},{"id":3,"color":"blue"},{"id":4,"color":"yellow"},{"id":5,"color":"green"},{"id":6,"color":"pink"},{"id":7,"color":"orange"},{"id":8,"color":"white"},{"id":9,"color":"teal"}]
// create the dictionary
const dict = _.keyBy(data2, 'id')
// get the items from the dictionary
const newData = data1.map(({ ids, ...item }) => ({ ...item, data: _.at(dict, ids) }))
console.log(newData)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>