Practical tips for handling JS objects

VUE3-toRef and toRefs

toRef

You can also create a corresponding ref based on a property on the responsive object. A ref created in this way is synchronized with its source property: changing the value of the source property will update the value of the ref, and vice versa.

toRefs

Convert a reactive object into a normal object. Each property of this normal object is a ref pointing to the corresponding property of the source object. Each individual ref is created using toRef().

code

<template>
  <h2>{
   
   {data}}</h2>
  <h2>计数器:{
   
   {counter1}}</h2>
  <button @click="counter1++">计数器加1</button>
  <hr>
  <h2>计数器2:{
   
   {counter2}}</h2>
  <button @click="counter2++">计数器加1</button>
  <hr>
  <h2>计数器3:{
   
   {a.b.counter3}}</h2>
  <button @click="a.b.counter3++">计数器加1</button>
</template>

<script>
  import {
    ref,
    toRef,
    reactive,
    toRefs
  } from 'vue'
  export default {
    setup() {
      // data
      let data = reactive({
        counter1: 1,
        counter2: 100,
        a: {
          b: {
            counter3: 1000
          }
        }
      })
      // 这样写肯定不行,因为这种方式第一次打开页面的时候,能够看到数据,但是不是响应式的。因为这个数据和data无关了
      // return {
      //   counter1: data.counter1,
      //   counter2: data.counter2,
      //   counter3: data.a.b.counter3
      // }
      // 下面这种方式可以完成响应式
      // 问题是什么?计数器加1的时候,data对象中的数据不会变
      // return {
      //   counter1: ref(data.counter1),
      //   counter2: ref(data.counter2),
      //   counter3: ref(data.a.b.counter3)
      // }
      // 因为上面这样写与下面的写法没有区别
      // return {
      //   counter1: ref(1),
      //   counter2: ref(100),
      //   counter3: ref(1000)
      // }
      // 由于上面的原因,则引入了下面toRef
      // toRef语法格式:toRef(对象,'该对象中的属性名')
      // toRef函数执行之后会生成一个全新的对象:objectRefImpl(引用对象)
      // 这个引用对象会与指定的数据形成响应式,相当于在两个数据直接搭建了桥梁
      // 只要有引用对象,就有value属性,并且value属性是响应式的。(value有对应的set和get。)
      console.log(toRef(data, 'counter1'));

      // return {
      //   data,
      //   counter1: toRef(data, 'counter1'),
      //   counter2: toRef(data, 'counter2'),
      //   counter3: toRef(data.a.b, 'counter3')
      // }
# 处理JS对象实用技巧

本文来分享 10 个开发技巧,可以使用这些技巧来高效地操作和使用 JavaScript 对象。

## 1. 创建一个绝对空的对象

我们可以通过 {} 来创建空对象。 然而,通过方法中创建的对象,proto、hasOwnProperty等对象方法仍然是存在的,这是因为使用 {} 将创建一个继承自 Object 类的对象。

如果需要创建一个绝对空的对象,最好使用 Object.create(null),它将创建一个不从任何对象继承且没有属性的对象。

```js
let vehical = Object.create(null);
// vehicle.__proto__ === "undefined"

2. Use the spread operator to combine two objects

In many cases, two or more data sets from different sources need to be combined.

The most common method is to use Object.assign(). This method requires several parameters. The first is the object to allocate, and the rest of the arguments are the objects that need to be combined.

const name = {
    
    
  id: '1234',
  name: 'Charuka'
};
const university = {
    
    
  id: '1234',
  university: 'Harvard'
};
const PersonalDetails = Object.assign({
    
    }, name, university);

console.log(PersonalDetails);
// { id: '1234', name: 'Charuka', university: 'Harvard' }

Combination is more convenient using the spread operator, just spread any number of objects and combine them into one object.

const PersonalDetails = {
    
    
  ...name,
  ...university
};

console.log(PersonalDetails);
// { id: '1234', name: 'Charuka', university: 'Harvard' }

It should be noted that if there are duplicate keys, the subsequent keys will overwrite the keys of the previous object.

3. Get a list of keys and values ​​from an object

During development, there are times when you need to get just the keys or just the values ​​from an object. This can be achieved through the following two built-in functions:

Object.keys(): used to get the key list.

Object.values(): used to get a list of values.

const vehicle = {
    
    
  brand: 'BWM',
  year: 2022,
  type: 'suv'
};
//获取键
console.log(Object.keys(vehicle)); // [ 'brand', 'year', 'type' ]
//获取值
console.log(Object.values(vehicle)); // [ 'BWM', 2022, 'suv' ]

4. Check properties

When using a for-in loop, checking the object's properties helps avoid iterating over properties in the object's prototype. You can use Object.hasOwnProperty() to check instead of using if-else.

const vehicle = {
    
    
  brand: 'BWM',
  year: 2022,
  type: 'suv'
};
for (var item in vehicle) {
    
    
  if (vehicle.hasOwnProperty(item)) {
    
    
    console.log(item);
  };
};
// brand
// year
// type

5. Clone objects

Suppose you have an object and need to copy it to change its value, but the original object should remain unchanged. This can be achieved by the following methods.

The first way is to use Object.assign(), which copies the values ​​of all enumerable properties from one object to another.

const initialVehicle = {
    
    
  brand: 'BWM',
  year: 2022,
  type: 'suv'
};
const secondaryVehicle = Object.assign({
    
    }, initialVehicle);
console.log(secondaryVehicle); // { brand: 'BWM', year: 2022, type: 'suv'};

The second method is to use JSON.parse() to copy the object.

var initialVehicle = {
    
    
  brand: 'BWM',
  year: 2022,
  type: 'suv'
};
var secondaryVehicle = JSON.parse(JSON.stringify(initialVehicle));
console.log(secondaryVehicle); // { brand: 'BWM', year: 2022, type: 'suv'};

6. Select specific data from an object

Different methods can be used to select specific keys in the object. The choice of selection method depends on what you want to do with the values. The following example shows a methodical way of selecting data from an object, with the possibility to select the required keys and extract them into a new object.

const selectObj = (obj, items) => {
    
    
  return items.reduce((result, item) => {
    
    
    result[item] = obj[item];
    return result;
  }, {
    
    });
};
const vehicle = {
    
    
  brand: 'BWM',
  year: 2022,
  type: 'suv'
};
const selected = selectObj(vehicle, ['brand', 'type']);
console.log(selected); // { brand: 'BWM', type: 'suv' }

7. Remove keys from objects

Sometimes we need to delete a specific key and its value from an object. The most appropriate approach is to write a reusable delete method that takes as input an object and a list of keys to delete. Then loop through each key you want to delete and delete it from the object.

const remove = (object, removeList = []) => {
    
    
  const result = {
    
    
    ...object
  };
  removeList.forEach((item) => {
    
    
    delete result[item];
  });
  return result;
}

const vehicle = {
    
    
  brand: 'BWM',
  year: 2022,
  type: 'suv'
}

const itemRemoved = remove(vehicle, ['year']);
console.log(itemRemoved); // Result { brand: 'BWM', type: 'suv' }

8. Pull object data into an array

In some cases, we need to pull object data into an array, such as a dropdown menu. You can use the Object.entries() function, which takes an object as its first argument and returns an array.

The result returned is a two-dimensional array. The inner array will have two values: the first is the key and the second is the value.

const vehicle = {
    
    
  brand: 'BWM',
  year: 2022,
  type: 'suv'
}
console.log(Object.entries(vehicle));
// [ [ 'brand', 'BWM' ], [ 'year', 2022 ], [ 'type', 'suv' ] ]

9. Loop through JavaScript objects

There are several methods in JavaScript for iterating over objects.

The first way is to use Object.entries(), which avoids looking up every value in the original object.

const vehicle = {
    
    
  brand: 'BWM',
  year: 2022,
  type: 'suv'
}
Object.entries(vehicle).forEach(
  ([key, value]) => console.log(key, value)
);
// brand BWM
// year 2022
// type suv

As a better and cleaner approach, Object.entries() can be used for object destructuring.

const vehicle = {
    
    
  brand: 'BWM',
  year: 2022,
  type: 'suv'
}
for (const [key, value] of Object.entries(vehicle)) {
    
    
  console.log(key, value);
}
// brand BWM
// year 2022
// type suv

10. Conditionally add properties to objects

Typically, developers use if-else to conditionally add new elements to objects. However, the easiest way is to use object destructuring and the spread operator.

const type = {
    
    
  type: 'suv'
};
const vehicle = {
    
    
  brand: 'BMW',
  year: 2022,
  ...(!type ? {
    
    } : type)
}
console.log(vehicle); //{ brand: 'BMW', year: 2022, type: 'suv' }

Also, using different conditions, any number of elements can be added to the object.

Involving content

JS, Object
// toRefs function usage: toRefs(data)
console.log(toRefs(data)) // This generates an object

  return {
    data,
    ...toRefs(data)
  }
  // 相当于上面简写相当于下面
  // return {
  //   data,
  //   counter1: toRef(data, 'counter1'),
  //   counter2: toRef(data, 'counter2'),
  //   a:{
  //     b:{
  //       counter3: toRef(data.a.b, 'counter3')
  //     }
  //   }
  // }
}

}


## 涉及内容

vue3、toRef、toRefs

Guess you like

Origin blog.csdn.net/MCCLS/article/details/132027489