cari

Rumah  >  Soal Jawab  >  teks badan

javascript - menyusun objek berdasarkan nilai dalam tatasusunan

var a = [100,200,300]

var b = [{id:'100',name:'Xiaohong'},{id:'300',name:'Xiaoming'},{id:'200',name:'Xiaolan'}]

我想大声告诉你我想大声告诉你2752 hari yang lalu563

membalas semua(5)saya akan balas

  • ringa_lee

    ringa_lee2017-05-19 10:48:17

    var a = [100,200,300];
    var b = [{id:'100',name:'小红'},{id:'300',name:'小明'},{id:'200',name:'小蓝'}];
    
    var result = b.sort((aa, bb) => (a.indexOf(aa.id - 0) - a.indexOf(bb.id - 0)));
    
    // 不考虑重复ID的话方法还有很多:
    result = a.map(el_a=>(b.find(el_b => el_b.id == el_a)));
    result = b.reduce((acc,cur) => (acc[a.indexOf(cur.id - 0)] = cur, acc), []);

    balas
    0
  • 仅有的幸福

    仅有的幸福2017-05-19 10:48:17

    var a = [100,200,300]
    var b = [{id:'100',name:'小红'},{id:'300',name:'小明'},{id:'200',name:'小蓝'}]
    
    function sortSome(a, b){
        var arr = [];
        a.forEach(function(tem, index){
          b.forEach(function(val, num){
            if(tem == val.id){
              arr.push(val);
          }
        })
      })
      return arr;
    }
    console.log(sortSome(a,b))

    balas
    0
  • PHP中文网

    PHP中文网2017-05-19 10:48:17

    let c=[];
    
    for(let num of a){
        b.forEach(item => {
            if(item.id == num) c.push(item)
        })
    }

    balas
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-19 10:48:17

    var a = [100,200,300]
        var b = [{id:'100',name:'小红'},{id:'300',name:'小明'},{id:'200',name:'小蓝'}]
         var obj={};
           b.forEach((x)=>{
               obj[x.id]=x
           })
           var arr=a.map((x)=>{
               return obj[x]
           })
           console.log(arr)

    balas
    0
  • 高洛峰

    高洛峰2017-05-19 10:48:17

    Hanya gelung sekali:

    b.forEach(function(ele, index, arr) {
        if (a.indexOf(parseInt(ele.id)) > -1)
            this[a.indexOf(parseInt(ele.id))] = ele;
    }, out = [])
    console.log(JSON.stringify(out));

    balas
    0
  • Batalbalas