我对来自lodash源代码的测试输出感到困惑:
我的任务是获取包含多个对象的地图的键。出于某种原因,我需要遍历地图并获取对象。以下是我的源代码:
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);
我希望我的result
为{'1': [ 1, 2, 3 ]}
或{'2': [ 2, 4, 6 ]}
,以便在我的迭代中获得1或2的密钥。
但我得到的是result
是[1,2,3]
或[2,4,6]
,我得到的密钥是[ undefined , undefined]
。
我对结果感到很困惑。有人可以解释吗? 谢谢!
答案 0 :(得分:1)
使用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.net/lodash/4.13.1/lodash.min.js"></script>
&#13;
var contacts = ['Billy Bob', 'John', 'Bill', 'Sarah'];
var filters = ['Bill', 'Sarah'];
contacts = _.filter(contacts, function(contact) {
return _.every(filters, function(filter) { return (contact.indexOf(filter) === -1); });
});
// ['John']
&#13;
答案 1 :(得分:1)
我想我不应该从一开始就使用地图,因为它返回
更理想的方式是:
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;
});