如何解决使用 lodash 在 JSON 中查找非空值的计数
let obj = [
{
id: 1,amount: null,},{
id: 2,amount: 123,{
id: 3,{
id: 4,{
id: 5,amount: 100,];
我需要使用 lodash 函数找到上述 JSON 响应中存在的非空值的数量。
我在下面的代码中使用了正常方式
for (var i = 0; i < obj.length; i++) {
if (obj[i]['amount'] != null) {
count++;
}
}
console.log(count);
谁能给出如何使用 lodash 做同样的事情的想法?
解决方法
您可以使用 _.sumBy()
并在不为假时返回 1(null
或 0):
const obj = [{"id":1,"amount":null},{"id":2,"amount":123},{"id":3,{"id":4,{"id":5,"amount":100}]
const result = _.sumBy(obj,({ amount }) => amount ? 1 : 0)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
另一种选择是使用 _.countBy()
来计算 amount
值是否为 null
的项目,并取 'false'
值:
const obj = [{"id":1,"amount":100}]
const result = _.countBy(obj,({ amount }) => _.isNull(amount))['false']
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
我们可以使用 lodash reduce 函数,我们也可以使用 filter,两者都可以得到您需要的结果:
const obj = [ { "id": 1,"amount": null },{ "id": 2,"amount": 123 },{ "id": 3,{ "id": 4,{ "id": 5,"amount": 100 } ]
let count = _.reduce(obj,(sum,row) => row.amount !== null ? sum + 1: sum,0);
console.log("Count using _.reduce:",count);
count = _.filter(obj,(row) => row.amount !== null).length;
console.log("Count using _.filter:",count);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
就像在 vanilla JavaScript 中一样,我认为对于 lodash 使用 reduce()
也是最好的方法:
const obj = [{
"id": 1,"amount": null
},{
"id": 2,"amount": 123
},{
"id": 3,{
"id": 4,{
"id": 5,"amount": 100
}];
const count = _.reduce(obj,((a,{amount}) => a + (amount != null ? 1 : 0)),0);
console.log(count);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
您也可以使用类似过滤器的方法,但会产生创建过滤数组的额外开销。
虽然真的没有必要为此使用 lodash:
const obj = [{
"id": 1,"amount": 100
}];
const count = obj.reduce(((a,0);
console.log(count);
在这里你真的不需要 lodash,一切都可以使用 vanilla JavaScript 轻松完成。您需要做的就是仅过滤掉具有数量的值,然后找到数组长度。
const obj = [
{
id: 1,amount: null,},{
id: 2,amount: 123,{
id: 3,{
id: 4,{
id: 5,amount: 100,];
const result = obj.filter((x) => x.amount !== null).length
console.log(result);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。