First let's analyse your code and detect some mistakes and then we will focus on the solution.
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})
);
In your code the function entries
does not return any value. Therefore, the console.log()
will return undefined
. We can fix this replacing var result =
with return
. So now your entries
function returns an array based on your object obj
. Like this:
function entries(obj) {
return 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
})
);
Now we can optimize a little bit let's define a two objects: objA
and objB
. the first one will be your first example.
let objA = { a: 1, b: 2, c: 3 };
let objB = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};
If you call console.log(entries(objA))
you wil get an NaN
error because the a
is not a number and you are using the Number()
method to cast the key
values. Let's removed that function call. Thi will be final version of the solution:
let objA = { a: 1, b: 2, c: 3 };
let objB = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};
function entries(obj) {
return Object.keys(obj).map(function(key) {
return [key, obj[key]];
});
}
console.log(entries(objA));
console.log(entries(objB));