I am confused by a testing output from my lodash source code:
My task is to get the keys of an map, which include multiple objects. For some reason, I need to loop through the map and get the object. Below is my source code:
var results = {"1":[1,2,3],"2":[2,4,6]};
var out = _.map(results, (result) => {
//console.log(result);
let key = _.keys(result);//I expect the key to be 1 or 2
//... doing something else with the value, I assume is [1,2,3] or [2,4,6]
});
console.log(out);
I was expecting my result
to be {'1': [ 1, 2, 3 ]}
or {'2': [ 2, 4, 6 ]}
so that I can get the key of 1 or 2, in my iteration.
But what I got was that the result
is [1,2,3]
or [2,4,6]
and the keys I got was [ undefined , undefined]
.
I am really confused about the result. Can someone interpret that? Thanks!
I am confused by a testing output from my lodash source code:
My task is to get the keys of an map, which include multiple objects. For some reason, I need to loop through the map and get the object. Below is my source code:
var results = {"1":[1,2,3],"2":[2,4,6]};
var out = _.map(results, (result) => {
//console.log(result);
let key = _.keys(result);//I expect the key to be 1 or 2
//... doing something else with the value, I assume is [1,2,3] or [2,4,6]
});
console.log(out);
I was expecting my result
to be {'1': [ 1, 2, 3 ]}
or {'2': [ 2, 4, 6 ]}
so that I can get the key of 1 or 2, in my iteration.
But what I got was that the result
is [1,2,3]
or [2,4,6]
and the keys I got was [ undefined , undefined]
.
I am really confused about the result. Can someone interpret that? Thanks!
Share Improve this question edited Nov 8, 2017 at 0:33 jsh6303 asked Nov 8, 2017 at 0:28 jsh6303jsh6303 2,0404 gold badges26 silver badges51 bronze badges 1-
I'm confused. If I'm reading your question correctly, you're saying that you expect
out
to be the same the input (results
)? – fubar Commented Nov 8, 2017 at 0:37
2 Answers
Reset to default 2I think I shouldn't used the map from all the start, since it returns
A more desired way is:
var results = {"1":[1,2,3],"2":[2,4,6]};
var out = _.each(results, (value, key) => {
console.log(key);
//Do something else with the value and get some `data`, which depends on both key and value
return data;
});
Use _.keys()
var results = {"1":[1,2,3],"2":[2,4,6]};
var out = _.keys(results, (result) => {
console.log(result);
//... doing something else
});
console.log(out);
<script src="https://cdn.jsdelivr/lodash/4.13.1/lodash.min.js"></script>