根据arr数组的顺序,把init里面的对象按照arr的顺序放,得出arr3数组
const arr = ['operation', 'age', 'name', 'address'];
const init = [{
title: 'name',
dataIndex: 'name',
width: '25%',
}, {
title: 'age',
dataIndex: 'age',
width: '15%',
}, {
title: 'address',
dataIndex: 'address',
width: '40%',
}, {
title: 'operation',
dataIndex: 'operation',
}]
let arr3 = [{
title: 'operation',
dataIndex: 'operation',
}, {
title: 'age',
dataIndex: 'age',
width: '15%',
}, {
title: 'name',
dataIndex: 'name',
width: '25%',
}, {
title: 'address',
dataIndex: 'address',
width: '40%',
}, ];
用数组sort下就行,排序回调中的2个a,b参数,分别找dataIndex在arr中的下标,升序用aIndex-bIndex,降序则bIndex-aIndex
const arr = ['operation', 'age', 'name', 'address'];
const init = [{
title: 'name',
dataIndex: 'name',
width: '25%',
}, {
title: 'age',
dataIndex: 'age',
width: '15%',
}, {
title: 'address',
dataIndex: 'address',
width: '40%',
}, {
title: 'operation',
dataIndex: 'operation',
}]
let arr3 = JSON.parse(JSON.stringify(init)).sort(function (a, b) {
var aIndex = arr.findIndex(i => a.dataIndex == i);
var bIndex = arr.findIndex(i => b.dataIndex == i);
return aIndex - bIndex;
})
console.log(arr3)
你可以使用JavaScript的Array.prototype.sort()方法来实现你的需求,它可以根据给定的比较函数来排序数组,代码如下:
```javascript
let arr3 = init.sort((a, b) => {
let indexA = arr.indexOf(a.title);
let indexB = arr.indexOf(b.title);
return indexA - indexB;
});
```
通过arr来进行map,在通过init来对arr中的值进行过滤,得到就是所要的数组,如下代码:
const arr = ['operation', 'age', 'name', 'address'];
let result = arr.map(it => init.filter(item => item.dataIndex === it)[0]);
console.log(result);
可以通过遍历 arr 数组,然后在 init 数组中查找对应的元素,将它添加到 arr3 数组中,从而实现根据 arr 数组的顺序重新排列 init 数组中的元素。
下面是一个示例代码:
const arr = ['operation', 'age', 'name', 'address'];
const init = [{
title: 'name',
dataIndex: 'name',
width: '25%',
}, {
title: 'age',
dataIndex: 'age',
width: '15%',
}, {
title: 'address',
dataIndex: 'address',
width: '40%',
}, {
title: 'operation',
dataIndex: 'operation',
}];
let arr3 = [];
arr.forEach((item) => {
const found = init.find((el) => el.dataIndex === item);
if (found) {
arr3.push(found);
}
});
这段代码会将重新排列后的结果存储在 arr3 数组中。
方法二
Array.prototype.map() 方法,结合 Array.prototype.find() 方法来实现按照 arr 数组的顺序放置 init 中的对象,并生成 arr3 数组,如下所示:
const arr3 = arr.map((key) => init.find((item) => item.dataIndex === key));
console.log(arr3);