当前位置:网站首页>js對JSON數組的增删改查

js對JSON數組的增删改查

2022-07-06 23:14:00 ~疆

目錄

查詢記錄。根據username查詢記錄

 删除記錄。根據username删除記錄

 修改記錄。根據username修改password

新增記錄。 


參考:JavaScript(js)中數組Array的常用方法_~疆的博客-CSDN博客_array jsArray.some()var arr=[1, 2, 3, 4, 5]var arr1=arr.some(x => x > 3);console.log(arr) //Array [1, 2, 3, 4, 5]console.log(arr1) //truesome() 方法用於檢測數組中的元素是否滿足指定條件(函數提供)。some() 方法會依次執行數組的每個元......https://blog.csdn.net/qq_40323256/article/details/103008280 

查詢記錄。根據username查詢記錄

    const users = [
      { username: "張三", password: 333 },
      { username: "李四", password: 444 },
      { username: "王五", password: 555 },
    ];

    //查詢記錄。根據username查詢記錄
    let data = users.filter((item) => item.username == "張三");
    console.log("根據username查詢出的記錄:", data);

 删除記錄。根據username删除記錄

    const users = [
      { username: "張三", password: 333 },
      { username: "李四", password: 444 },
      { username: "王五", password: 555 },
    ];

    //删除記錄。根據username删除記錄
    let data = users.filter((item) => item.username == "張三");
    console.log("根據username查詢出的記錄:", data);
    let index = users.indexOf(data[0]);
    console.log("索引index:", index);
    index !== -1 && users.splice(index, 1);
    console.log("删除一條記錄後的users:", users);

 修改記錄。根據username修改password

    const users = [
      { username: "張三", password: 333 },
      { username: "李四", password: 444 },
      { username: "王五", password: 555 },
    ];

    //修改記錄。根據username修改password
    let data = users.filter((item) => item.username == "張三");
    console.log("根據username查詢出的記錄:", data);
    data[0].password = 3333;
    console.log("修改一條記錄後的users:", users);

新增記錄。 

 

    const users = [
      { username: "張三", password: 333 },
      { username: "李四", password: 444 },
      { username: "王五", password: 555 },
    ];

    //新增記錄。
    users.push({ username: "趙六", password: 666 });
    console.log("新增一條記錄後的users:", users);

原网站

版权声明
本文为[~疆]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061541055682.html