欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JS 交换对象中属性的顺序,交换数组对象中对象的顺序

程序员文章站 2022-07-06 15:20:56
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

相关标签: js object