JS - Determine whether a certain element/key (key) exists in array/object

Requirement: Determine whether each item in the array hastaskCountfield

Data Format

boxList:[
          {
    
     type:1,status:0, taskCount:'',barcode:'001',},
          {
    
     type:2,status:2, taskCount:0,barcode:'052',},
          {
    
     type:3,status:1, taskCount:120,barcode:'034',}
       ]

<div  v-for="items in  boxList" :key="items.groupId" >
   <div class="lock-task" v-if="item.hasOwnProperty('taskCount')">
   </div>
 </div>

item.hasOwnProperty(‘taskCount’)

1. Determine whether a certain key exists in the Object

let obj={
    
    
      name:'张三', 
      sex:'男'
}

js method

method 1:

Object.hasOwnProperty.call(obj,'name'); // true
Object.hasOwnProperty.call(obj,'age'); // false

Method 2:

obj.hasOwnProperty('name'); // true
obj.hasOwnProperty('age'); // false

Method 3:

'name' in obj; // true
'age' in obj; // false

2. Determine whether a certain key exists in the Object in the array

2.1. Determine whether a certain key exists in the Object in the array

arr = [
  {
    
    name:'张三', sex:'男'},
  {
    
    name:'李四', sex:'男'},
  {
    
    name:'王五', sex:'男'},
];

js method

方法1
arr.some(item=>Object.hasOwnProperty.call(item,'name')); // true
arr.some(item=>Object.hasOwnProperty.call(item,'age')); // false

方法2
arr.some(item=>item.hasOwnProperty('name')); // true
arr.some(item=>item.hasOwnProperty('age')); // false

方法3
arr.some(item=>'name' in item); // true
arr.some(item=>'age' in item); // false

2.2. Determine whether there is an element that meets the condition in the Object in the array

arr = [
  {
    
    name:'张三', sex:'男', age:11},
  {
    
    name:'李四', sex:'男', age:22},
];

JS method:

arr.some(item => item.name === '张三'); // true
arr.some(item => item.name === '王五'); // false

2.3 Determine whether there is an element that meets the condition in the Object in the array, and return all elements that meet the condition

arr = [
  {
    
    name:'张三', sex:'男', age:11},
  {
    
    name:'李四', sex:'男', age:22},
  {
    
    name:'王五', sex:'男', age:33},
];

js method

const list = arr.filter(item => item.age === 11);
console.log(list); //  [{ name: '张三', sex: '男', age: 11 },{ name: '王五', sex: '男', age: 11 }]

Guess you like

Origin blog.csdn.net/Maxueyingying/article/details/134160402