Search code examples
javascriptsub-array

Return an array of arrays of key-value pairs WITHOUT using Object.entries()


I am trying to write a function that accepts an object and returns an array of arrays of key-value pairs. I also cannot use the Object.entries() function.

Example: For var obj = { a: 1, b: 2, c: 3 }; I would want to return: [["a",1], ["b",2], ["c",3]]

Here is what I have written so far:

function entries(obj) {

var result = Object.keys(obj).map(function(key) {
  return [Number(key), obj[key]];
});
}
console.log(
  entries(obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0})
  );

However, I can only get it to return undefined at this point. What exactly am I doing incorrectly here?


Solution

  • You can do a simple for loop

    var obj= {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
    var arr=[]
    for(var item in obj){
      arr.push([item,obj[item]])
    }
    console.log(arr)