JS adds, deletes, modifies and checks JSON arrays

The following is a detailed example of adding, deleting, modifying and querying JSON arrays using JavaScript:

// 创建一个空的JSON数组
let data = [];

// 添加数据
function addData(item) {
  data.push(item);
  console.log(`已添加数据:${JSON.stringify(item)}`);
}

// 删除数据
function deleteData(item) {
  const index = data.findIndex((d) => JSON.stringify(d) === JSON.stringify(item));
  if (index !== -1) {
    data.splice(index, 1);
    console.log(`已删除数据:${JSON.stringify(item)}`);
  } else {
    console.log('数据不存在');
  }
}

// 更新数据
function updateData(oldItem, newItem) {
  const index = data.findIndex((d) => JSON.stringify(d) === JSON.stringify(oldItem));
  if (index !== -1) {
    data[index] = newItem;
    console.log(`已更新数据:${JSON.stringify(oldItem)} -> ${JSON.stringify(newItem)}`);
  } else {
    console.log('数据不存在');
  }
}

// 查询数据
function queryData() {
  console.log('当前数据:', data);
}

// 添加数据
addData({ name: 'Apple', price: 2 });
addData({ name: 'Banana', price: 3 });
addData({ name: 'Orange', price: 4 });

// 查询数据
queryData();

// 更新数据
updateData({ name: 'Banana', price: 3 }, { name: 'Mango', price: 5 });

// 删除数据
deleteData({ name: 'Apple', price: 2 });

// 查询数据
queryData();

In this example, we first create an empty JSON array `data`. Then, we defined a series of functions to perform addition, deletion, modification and query operations on JSON arrays.

The `addData` function is used to add data to the JSON array. We can pass the data that needs to be added to this function as a parameter and use the `push` method to add the data to the array.

The `deleteData` function is used to delete data in a JSON array. We need to pass the data to be deleted as a parameter to this function. The function uses the `findIndex` method to find the index of the data to be deleted in the array, and then uses the `splice` method to remove it from the array.

The `updateData` function is used to update the data in the JSON array. We need to pass old data and new data as parameters to this function. The function uses the `findIndex` method to find the index of the old data in the array and replace it with the new data.

The `queryData` function is used to query the data in the JSON array and print it out.

In the example, we first added three JSON objects to the array. We then queried the current data and updated the price of Banana to 5. Next, we deleted a JSON object and queried the updated data again.

Through this example, you can see how to use JavaScript to add, delete, modify and query JSON arrays. These concepts and methods are very useful in practical development, especially when dealing with data collections.
 

Guess you like

Origin blog.csdn.net/weixin_39273589/article/details/132624700