这里的对象里面有数组,如何检查对象数组的长度?

时间:2018-12-19 09:13:03

标签: javascript angular typescript

下面是我的数据

var a=[
        {
            name: "time",
            Details:[
                {value:"month",checked:true,id:1}
            ]
        },
        {
            name: "product",
            Details:[
                {value:"abc",checked:true,id:2},
                {value:"abx",checked:false,id:3}
            ]
        }
    ]

我想找到已检查的数量。在示例中,count是2如何以优化的方式进行操作(没有for循环,没有filter的过滤器)。

4 个答案:

答案 0 :(得分:2)

您可以在此处使用标准减速器。

const a=[
  {
    name: "time",
    Details:[
    {value:"month",checked:true,id:1}
    ]
  },
  {
    name: "product",
    Details:[
    {value:"abc",checked:true,id:2},
    {value:"abx",checked:false,id:3}
    ]
  }
]


const total = a.reduce((total, entry) => total + entry.Details.reduce((all, inner) => all + (inner.checked === true ? 1 : 0), 0), 0)

console.log(total);

以更具可读性的方式再次出现:

const total = a.reduce((total, item) => {
  // add the total to a result of adding up items in the inner arra
  return total + item.Details.reduce((innerTotal, entry) => {
    // for inner item, we add 1 if the entry is checked.
    if (entry.checked) {
      return innerTotal + 1;
    }
    // otherwise, just return the current total.
    return innerTotal;
  }, 0), // innerTotal starts at 0
 }, 0);  // and so does the outer total.

答案 1 :(得分:1)

您需要在嵌套模式中使用两个forEach()

var a = [{
    name: "time",
    Details: [{
      value: "month",
      checked: true,
      id: 1
    }]
  },
  {
    name: "product",
    Details: [{
        value: "abc",
        checked: true,
        id: 2
      },
      {
        value: "abx",
        checked: false,
        id: 3
      }
    ]
  }
];

var count = 0;
a.forEach(({Details}) => Details.forEach(({checked}) => {
  if(checked){
    count++;
  }
}))
console.log(count);

答案 2 :(得分:0)

尝试此操作,我希望它一定会对您有用

    let Count=0;
var a=[
            {
                name: "time",
                Details:[
                    {value:"month",checked:true,id:1}
                ]
            },
            {
                name: "product",
                Details:[
                    {value:"abc",checked:true,id:2},
                    {value:"abx",checked:false,id:3}
                ]
            }
        ];
a.map(function(value,index){
value.Details.map(function(innerValue, innerIndex){
if( innerValue.checked==true){
Count++;
}
});
}); 

答案 3 :(得分:0)

您可以组合使用多个功能来获取带有已检查值的所有详细信息:

a.map(t => t.Details).flat().filter(t=>t.checked)

首先绘制一张地图,然后将结果分成一个数组,然后按选中进行过滤