Summary of some scenarios of common array data processing in front-end work

1. Modify the array and return a new array;

01. Description.

In our work, we often find that some of the data sent from the backend not only has empty key values, but also has no keys, which is what we often call attribute names. Then we need to modify it to return a data with a normal structure;

02. Code.

const data = [
	{ id: 1, name: 'John' ,age:''},
    { id: 2 },
	{ name: 'Jane' },
	{ id: 3, age: 30 }
];
const filteredData = data.map(item => ({...item, id: item.id || '不存在',age:item.age||'不存在啊1'}));

03. Summary.

Using map is a very convenient array method. It can return a new array, and the amount of code is greatly reduced. If you don’t know much about map for beginners, you can check the syntax of es6 and find out the difference between forEach and forEach.

2. Determine whether the element is a null character for the array element.

01. Description.

For example, in the case of dictation, some data needs to be judged. All data elements cannot be empty strings, and must have content to pass parameters to the interface.

02. Code implementation.

const data = [
		  { id: 1, name: 'John' ,age:''},
		  { id: 2 },
		  { name: 'Jane' },
		  { id: 3, age: 30 }
		];
		let tag = ''
		const ss = ['id','name','age']
		for(let i=0;i<data.length;i++){
			for(let j=0;j<ss.length;j++){
				if(data[i][ss[j]]===''){
					tag = true
					break
				}
			}
		}
		console.log(tag);

03. Summary.

Double for loops are very commonly used in work and must be taken seriously.

Big coffee passing by, if you like it, give it a thumbs up! Many thanks!

3. Make a copy of the object by means of the Object.keys() method;

01. Description.

When we need to copy an object, we need to know whether the object is an empty object, and perform forIN traversal on it, and often use its Object.keys() method.

The following is a set of data sent by the parent component, which is monitored and changed.

02. Code implementation.

watch: {
    checkouts: {
      handler: function(newV, oldV) {
        const o = { ...newV }
        //把对象属性转为一个数组  (其实这一步也可以直接对o==={}进行判断也是可以的)
        const key = Object.keys(o)
        if (key.length > 0) {
          for (const key in o) {
            this.queryAdd[key] = o[key]
          }
        }
      },
      deep: true
    }
  },

03. Summary.

We can often use the combination of objects and arrays to handle many scenarios. The easy-to-use Object.keys()

Guess you like

Origin blog.csdn.net/2201_75705263/article/details/132049087