让我说我有一个基本数组
let object2 = ["DotNet", "ETL", "Hadoop", "Java", "Oracle", "Pega", "MainFrame"]
我想按基本数组的相同顺序对第二个数组进行排序
let object1 = [{Name: "Java", ResourceCount: 3}, {Name: "DotNet", ResourceCount: 4}, {Name: "Hadoop", ResourceCount: 1}, {Name: "Pega", ResourceCount: 2}, {Name: "Oracle", ResourceCount: 1}, {Name: "ETL", ResourceCount: 1}, {Name: "MainFrame", ResourceCount: 0}]
所以看起来像这样
object1 =
[{Name: "DotNet", ResourceCount: 4},
{Name: "ETL", ResourceCount: 1},
{Name: "Hadoop", ResourceCount: 1},
{Name: "Java", ResourceCount: 3},
{Name: "Oracle", ResourceCount: 1},
{Name: "Pega", ResourceCount: 2},
{Name: "MainFrame", ResourceCount: 0}]
没有硬编码怎么办?
答案 0 :(得分:1)
一种可能的解决方案是使用Array.map
来迭代您的顺序名称列表-并将每个String
“映射”到对象列表中的相关对象中。
使用Array.find
完成关联,该const list1 = ["DotNet", "ETL", "Hadoop", "Java", "Oracle", "Pega", "MainFrame"];
const list2 = [{Name: "Java", ResourceCount: 3}, {Name: "DotNet", ResourceCount: 4}, {Name: "Hadoop", ResourceCount: 1}, {Name: "Pega", ResourceCount: 2}, {Name: "Oracle", ResourceCount: 1}, {Name: "ETL", ResourceCount: 1}, {Name: "MainFrame", ResourceCount: 0}];
const ordered = list1.map(function(nameValue) {
return list2.find((obj) => (obj.Name === nameValue));
});
console.log(ordered);
接收返回相关对象的函数作为参数:
{{1}}
答案 1 :(得分:0)
let object2 = ["DotNet", "ETL", "Hadoop", "Java", "Oracle", "Pega", "Mainframe"]
let object1 = [{Name: "Java", ResourceCount: 3}, {Name: "DotNet", ResourceCount: 4}, {Name: "Hadoop", ResourceCount: 1}, {Name: "Pega", ResourceCount: 2}, {Name: "Oracle", ResourceCount: 1}, {Name: "ETL", ResourceCount: 1}, {Name: "Mainframe", ResourceCount: 0}]
var arr=[]
object2.map(item=>{
object1.map(data=>{
if(data.Name===item)
{
arr.push(data)
}
})
})
console.log(arr)