How to convert an Object {} to an Array [] of key-value pairs in JavaScript

前端 未结 18 2310
名媛妹妹
名媛妹妹 2020-11-22 12:58

I want to convert an object like this:

{\"1\":5,\"2\":7,\"3\":0,\"4\":0,\"5\":0,\"6\":0,\"7\":0,\"8\":0,\"9\":0,\"10\":0,\"11\":0,\"12\":0}

18条回答
  •  天命终不由人
    2020-11-22 13:23

    To recap some of these answers now on 2018, where ES6 is the standard.

    Starting with the object:

    let const={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
    
    • Just blindly getting the values on an array, do not care of the keys:

    const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
    console.log(Object.values(obj));
    //[9,8,7,6,5,4,3,2,1,0,5]

    • Simple getting the pairs on an array:

    const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
    console.log(Object.entries(obj));
    //[["1",9],["2",8],["3",7],["4",6],["5",5],["6",4],["7",3],["8",2],["9",1],["10",0],["12",5]]

    • Same as previous, but with numeric keys on each pair:

    const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
    console.log(Object.entries(obj).map(([k,v])=>[+k,v]));
    //[[1,9],[2,8],[3,7],[4,6],[5,5],[6,4],[7,3],[8,2],[9,1],[10,0],[12,5]]

    • Using the object property as key for a new array (could create sparse arrays):

    const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
    console.log(Object.entries(obj).reduce((ini,[k,v])=>(ini[k]=v,ini),[]));
    //[undefined,9,8,7,6,5,4,3,2,1,0,undefined,5]

    This last method, it could also reorganize the array order depending the value of keys. Sometimes this could be the desired behaviour (sometimes don't). But the advantage now is that the values are indexed on the correct array slot, essential and trivial to do searches on it.

    • Map instead of Array

    Finally (not part of the original question, but for completeness), if you need to easy search using the key or the value, but you don't want sparse arrays, no duplicates and no reordering without the need to convert to numeric keys (even can access very complex keys), then array (or object) is not what you need. I will recommend Map instead:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

    let r=new Map(Object.entries(obj));
    r.get("4"); //6
    r.has(8); //true
    

提交回复
热议问题