数组对象内需要按照指定顺序排序,应该怎么排呢

huyouooo
  • 24
转换前 按照arr中的顺序排序
arr = ['b','a','d','c']
options = [
{ a:'0.89', b:'45', c:'77', d:'67'},
{ a:'546', b:'7', c:'8', d:'8'},
{ a:'78', b:'7', c:'9', d:'6'},
{ a:'0.5', b:'gg', c:'ert', d:'wer'},
]

转换后
result = [

{ b:'45', a:'0.89', d:'67',  c:'77' },
{ b:'7', a:'546', d:'8', c:'8'},
{ b:'00',a:'78', d:'6', c:'9'},
{ b:'gg', a:'0.5', d:'wer', c:'ert'}
]
回复
阅读 1k
2 个回答
✓ 已被采纳

arr = ['b', 'a', 'd', 'c']

    options = [
        { a: '0.89', b: '45', c: '77', d: '67' },
        { a: '546', b: '7', c: '8', d: '8' },
        { a: '78', b: '7', c: '9', d: '6' },
        { a: '0.5', b: 'gg', c: 'ert', d: 'wer' },
    ]
    let arr1 = []
    options.forEach(item => {
        let obj = {}
        arr.forEach(val => {
            obj[val] = item[val]
        })
        arr1.push(obj)
    });

Object里面的key是有默认排序规则的,无法手动控制顺序

可以保留arr按照顺序获取就好

宣传栏