JS 交换对象中属性的顺序,交换数组对象中对象的顺序
程序员文章站
2022-03-12 21:21:22
1.交换对象中属性顺序let obj = {name: 'joker',height: 183,weight: '70kg',sex: 'man',...}现在将性别属性移至对象中第二位let keyArr = Object.keys(obj)keyArr.splice(keyArr.indexOf('sex'), 1)keyArr.splice(1,0,'sex')let newObj = {}for (let idx = 0; idx < keyArr.len...
1.交换对象中属性顺序
let obj = {
name: 'joker',
height: 183,
weight: '70kg',
sex: 'man',
...
}
现在将性别属性移至对象中第二位
let keyArr = Object.keys(obj)
keyArr.splice(keyArr.indexOf('sex'), 1)
keyArr.splice(1,0,'sex')
let newObj = {}
for (let idx = 0; idx < keyArr.length; idx++) {
newObj[keyArr[idx]] = obj[keyArr[idx]]
}
console.log(newObj) // {name: "joker", sex: "man", height: 183, weight: "70kg"}
2. 交换数组对象中对象的顺序
let arr = [
{name: 'joker', age: 18},
{name: 'lisa', age: 20},
{name: 'lucky', age: 12},
{name: 'jak', age: 24},
{name: 'rose', age: 22}
]
现将jak所属的对象移至数组的第二位
let arrName = []
arr.forEach(el => {
arrName.push(el.name)
})
if (arrName.indexOf('jak') > -1) {
let filterArr = arr.splice(arrName.indexOf('jak'), 1)
arr.splice(1,0,filterArr [0])
}
console.log(arr)
//[{name: "joker", age: 18},
// {name: "jak", age: 24},
// {name: "lisa", age: 20},
// {name: "lucky", age: 12},
// {name: "rose", age: 22}]
本文地址:https://blog.csdn.net/Wangyhl/article/details/112529222